Error using ^, inputs must be scalar and square matrix
6 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
James Tursa
on 11 Oct 2016
Edited: James Tursa
on 11 Oct 2016
Use element-wise power and element-wise divide:
func=@(x) (1./(1+x.^2))
0 Comments
More Answers (1)
Corali Palomino
on 1 Jun 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
2 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!