Error using ^, inputs must be scalar and square matrix

조회 수: 11 (최근 30일)
AW
AW 2016년 10월 11일
댓글: Corali Palomino 2019년 6월 2일
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.

채택된 답변

James Tursa
James Tursa 2016년 10월 11일
편집: James Tursa 2016년 10월 11일
Use element-wise power and element-wise divide:
func=@(x) (1./(1+x.^2))

추가 답변 (1개)

Corali Palomino
Corali Palomino 2019년 6월 1일
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
Stephen23
Stephen23 2019년 6월 1일
You might need to use element-wise times: .*
Corali Palomino
Corali Palomino 2019년 6월 2일
Thank youuuuu!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by