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

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일

1 개 추천

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일
I know but if I want to use this for loop, how to plot it ?
It make no sense, but one option is:
plot(0,0);
h = findobj(gca,'Type','Line');
for i = 0:0.1:2*pi
m=sin(i);
n=i;
set(h,'XData',[get(h,'XData'),n])
set(h,'YData',[get(h,'YData'),m])
end
Xing Xing
Xing Xing 2019년 6월 5일
I was tried my code in old version of MATLAB and it works, but in 2018b which is the version I have right now it doesn't work. It's really weird and I don't understand. Thank you for your help and option! Really appreciated!
Alex Mcaulley
Alex Mcaulley 2019년 6월 5일
편집: Alex Mcaulley 2019년 6월 5일
With your code, you are generating one point in each iteration, not a unique line. If you want to see it:
for i = 0:0.1:2*pi
m=sin(i);
n=i;
plot(n,m,'*r');
hold on
end
numel(findobj(gca,'Type','Line'))
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일

0 개 추천

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!

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

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

태그

질문:

2019년 6월 5일

댓글:

2019년 8월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by