help me with for loop

조회 수: 2 (최근 30일)
nirwana
nirwana 2023년 9월 15일
답변: William Rose 2023년 9월 23일
I know this is very basic question, but i still has difficulty to answer it
i try to add some fourier series to prove gibbs effect
here my coding
t=0:0.01:7;
%odd series
yo= sin(t) + sin(3*t)/3 + sin(5*t)/5 + sin(7*t)/7 + sin(9*t)/9+sin(11*t)/11;
yoo=sin(13*t)/13+sin(15*t)/15+sin(17*t)/17+sin(19*t)/19+sin(21*t)/21;
subplot(211), plot(t,(yo+yoo)),title('fourier odd series')
%even series
ye= sin(0*t) + sin(2*t)/2 + sin(4*t)/4 + sin(6*t)/6 + sin(8*t)/8+sin(10*t)/10;
subplot(212), plot(t,ye), title('fourier even series')
instead of putting long equation, i would like to put it in for loop. can you help me to "rearange" my code neatly in foor loop.
my other question is : which one better to do it, for loop or vectorization (my teacher said that foor loop) must be avoid because it slower computational time
  댓글 수: 1
Stephen23
Stephen23 2023년 9월 15일
편집: Stephen23 2023년 9월 15일
"which one better to do it, for loop or vectorization (my teacher said that foor loop) must be avoid because it slower computational time"
For such a simple calculation I doubt there would be much difference. Overall (code runtime + write time + debug time + maintenance time) vectorized code is more efficient: you already have it and presumably it does what you want.
But go ahead: test them both and let us know.
"instead of putting long equation, i would like to put it in for loop. can you help me to "rearange" my code neatly in foor loop."
There are two posisble things you could loop over: 1) the elements of t or 2) the terms of the fourier series: which one do you want to loop over?

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

채택된 답변

William Rose
William Rose 2023년 9월 23일
@Stephen23 knows more about Matlab than almost anybody. When he says "I doubt there is much of a difference", I think he knows the answer and he is encouraging you to find out for yourself.
Your other question was how to replace a line such as
t=(0:.01:2)*2*pi;
yo= sin(t) + sin(3*t)/3 + sin(5*t)/5 + sin(7*t)/7 + sin(9*t)/9+sin(11*t)/11;
with a for loop.
yoloop=0;
for i=1:2:11
yoloop=yoloop+sin(i*t)/i;
end
Plot result
plot(t,yo,'-rx',t,yoloop,'-go');
legend('yo','yoloop')
You can see the GIbbs effect. Try this idea for yoo and ye.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by