Error using ^, inputs must be scalar and square matrix

28 visualizzazioni (ultimi 30 giorni)
SO I'm writing a Lagrange polynomial code and I've hit another error. I'm trying to evaluate a function at x over multiple points.
function f=larange2(func,n)
xi=linspace(-1,1,n);
yi=func(xi);
value=1;
zi=linspace(-1,1,100);
l=0;
ziy=[];
valuel=0;
for i=0:n
for c=0:n
if c~=i
value=value*((zi(i)-xi(c))/(xi(i)-xi(c)));
end
if c==n
ziy(i)=(value*yi(i));
end
end
end
for i=0:ziy.length()
valuel=valuel+ziy(i);
end
f=valuel;
end
I'm getting an issue when calling the function
func=@(x) (1/(1+x^2));
values=larange2(func,3);
end
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
Error in @(x)(1/(1+x^2))
Error in larange2 (line 4)
yi=func(xi);
Error in runl (line 3)
values=larange2(func,3);
SO what I'm asking, if I have an array of x values Xi (linspace gives me n evenly spaced points on an interval), and I want to calculate the y values into Yi for each x, what is the proper way to do it? A loop? My professor said that matlab would perform the function automatically as an array but it seems that there is a problem evaluating the function at x.

Risposta accettata

James Tursa
James Tursa il 11 Ott 2016
Modificato: James Tursa il 11 Ott 2016
Use element-wise power and element-wise divide:
func=@(x) (1./(1+x.^2))

Più risposte (1)

Corali Palomino
Corali Palomino il 1 Giu 2019
Hi, I have similar problems with "^", please somebody help me
this one: y=cos(x/2).^2*sin(x/2).^4
and this one: y=(25+x^2)^(-1.5)*2*x

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by