the last output given using for loop

1 回表示 (過去 30 日間)
Lorenne
Lorenne 2018 年 6 月 5 日
編集済み: Stephen23 2018 年 6 月 5 日
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

採用された回答

Stephen23
Stephen23 2018 年 6 月 5 日
編集済み: Stephen23 2018 年 6 月 5 日
"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) = ...

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by