the last output given using for loop

1 Ansicht (letzte 30 Tage)
Lorenne
Lorenne am 5 Jun. 2018
Bearbeitet: Stephen23 am 5 Jun. 2018
May i know why the following for loop produces e(end) of only n=5 and not from n=1?
e = linspace(-pi,pi,5);
>> d=1;
>> for n=1:length(e)
e(end)=n*d+3/2;
end

Akzeptierte Antwort

Stephen23
Stephen23 am 5 Jun. 2018
Bearbeitet: Stephen23 am 5 Jun. 2018
"why the following for loop produces e(end) of only n=5..."
You define a vector e with five elements:
e = linspace(-pi,pi,5);
Then in the loop you always refer to the last element of that vector, which is the fifth element:
e(end) = ...
You never refer to any other element, only the last (fifth) one, so each new values that you calculate in that loop is put into the same location in e : into the last element (the fifth) one. So on each iteration you simply replace the last value. That is what you wrote your code to do.
"... and not from n=1?"
If you want to access each element like that then the index will need to change, e.g. with the loop index:
e(n) = ...

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