the last output given using for loop

1 visualización (últimos 30 días)
Lorenne
Lorenne el 5 de Jun. de 2018
Editada: Stephen23 el 5 de Jun. de 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

Respuesta aceptada

Stephen23
Stephen23 el 5 de Jun. de 2018
Editada: Stephen23 el 5 de Jun. de 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) = ...

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by