Error using ^, inputs must be scalar and square matrix

12 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by