How to plot this function

3 ビュー (過去 30 日間)
O Kyung Kwon
O Kyung Kwon 2020 年 5 月 4 日
回答済み: Johannes Hougaard 2020 年 5 月 4 日
I want to plot y for x this equation.
y = 1/2 for x = 0
sin(pi*x/2)/(x*pi) for otherwise
So, I write this code. but It doesnt work. Help me friends.
x = -100:0.1:100;
if x == 0
y = 1/2;
else
y = sin(pi*x/2)/(x*pi);
end
plot(x, y);

採用された回答

KSSV
KSSV 2020 年 5 月 4 日
x = -100:0.1:100;
y = sin(pi*x/2)./(x*pi);
y(x==0) = 1/2 ;
plot(x, y);
  1 件のコメント
O Kyung Kwon
O Kyung Kwon 2020 年 5 月 4 日
thx, bro

サインインしてコメントする。

その他の回答 (1 件)

Johannes Hougaard
Johannes Hougaard 2020 年 5 月 4 日
You need to use the element-wise multiplication/division (.* or ./) rather than the matrix based multiplication (* or /).
...and then do the zeroexemption afterwards
This code should do the trick:
x = -100:0.1:100;
y = sin(pi.*x/2)./(x.*pi);
y(x==0) = 1/2;
plot(x,y);
If you were to do it in a for loop (which I'd strongly disadvice, but it can be useful to know for other purposes) it would be:
x = -100:0.1:100;
y = ones(size(x)); %pre-allocating for speed
for ii = 1:length(x)
if x(ii) == 0
y(ii) = 1/2;
else
y(ii) = sin(pi.*x(ii)/2)./(x(ii).*pi);
end
end
plot(x,y);
The for-loop is a tenfold slower and more complex...

カテゴリ

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