How to plot sine graph by using for loop?

18 ビュー (過去 30 日間)
Xing Xing
Xing Xing 2019 年 6 月 5 日
コメント済み: AZEEM IMTIAZ 2019 年 8 月 4 日
I tried to use a for loop to plot a sine graph. The values are generated but then when I try to graph them, I get either an error or no graph. Here's my code:
for i = 0:0.1:2*pi
m=sin(i);
n=i;
plot(n,m,'-r');
hold on
end
  2 件のコメント
Mohammad Alhashash
Mohammad Alhashash 2019 年 6 月 5 日
do you want to animate the sine graph or just plot it
Xing Xing
Xing Xing 2019 年 6 月 5 日
I just want to plot it with this for loop.

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

採用された回答

Alex Mcaulley
Alex Mcaulley 2019 年 6 月 5 日
You don't need a loop, just:
theta = 0:0.1:2*pi;
plot(theta,sin(theta))
  6 件のコメント
Xing Xing
Xing Xing 2019 年 6 月 5 日
OH, I see! Thanks!
AZEEM IMTIAZ
AZEEM IMTIAZ 2019 年 8 月 4 日
you need to define t as a continuous variable in the first line then apply for loop on the frequency as discrete values. so that each frequency point will sweep over the time that you have defined in the first line. hope this helps!
t=0:0.04:5;
hold on
for f=[0.7 1 1.5 2]
y=cos(2*pi*f*t);
plot(t,y)
end

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

その他の回答 (1 件)

Mohammad Alhashash
Mohammad Alhashash 2019 年 6 月 5 日
maybe that is what you need.
t= 0:0.01:2*pi;
m =sin(t);
t_plot = NaN(1,length(t));
m_plot = NaN(1,length(m));
u = 1;
for i = 1:length(t)
cla
t_plot(i) = t(u);
m_plot(i) = m(u);
plot(t_plot,m_plot)
drawnow
u = u + 1;
end
  1 件のコメント
Xing Xing
Xing Xing 2019 年 6 月 5 日
I understand what is my problem and thank you for your answer!

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

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by