the last output given using for loop

1 view (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 5 Jun 2018
Edited: Stephen23 on 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) = ...

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!