whats wrong with the code?

function fx=f(x)
for i=1:length(x)
if x(i)<0
fx(i)=x(i);
elseif x(i)==0:pi/2;
fx(i)=sin(x(i));
else
fx(i)=(sin(x(i)))
end
end
end

回答 (2 件)

Thorsten
Thorsten 2015 年 10 月 7 日
編集済み: Guillaume 2015 年 10 月 7 日

1 投票

x(i)==0:pi/2
compares x(i) to 0 and 1 (largest integer below pi/2) and gives the result in matrix of size 1x2. A matrix is considered to be true if all values are nonzero. Since x cannot be 0 and 1 at the same time, this never becomes true.
The code after else gives the same result as in the elseif before, so it does not make sense to differ between the two cases.
You don't need a for loop but you can use logical indexing to write your code, e.g.
fx(x<0) = x(x<0);
fx(x>=0 & x <= pi/2) = sin(x(x>=0 & x <= pi/2));
fx(x>pi/2) = -sin(x>pi/2);
Star Strider
Star Strider 2015 年 10 月 7 日

0 投票

I would re-code your elseif line to:
elseif (x(i)>=0) & (x(i) <= pi/2)

1 件のコメント

Image Analyst
Image Analyst 2015 年 10 月 7 日
Why & instead of &&?

この質問は閉じられています。

タグ

タグが未入力です。

質問済み:

2015 年 10 月 7 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by