Filter löschen
Filter löschen

help me with for loop

3 Ansichten (letzte 30 Tage)
nirwana
nirwana am 15 Sep. 2023
Beantwortet: William Rose am 23 Sep. 2023
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 Kommentar
Stephen23
Stephen23 am 15 Sep. 2023
Bearbeitet: Stephen23 am 15 Sep. 2023
"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?

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

William Rose
William Rose am 23 Sep. 2023
@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.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by