Create vector for data after each iteration of a for loop

I can't seem to figure out how to make a vector that after each iteration of a for loop takes the value of the set variable, and adds a data point. Below I added a pseudo-code example of what I'm trying to accomplish. When I try to make anything of the sort, it just overwrites the previous value.
y = x;
z = 0*y;
for n = 0:N
z = Z+1+2.*n
end
How can I, after N iterations, make a column vector(e.g. Vect) that does the following:
Iteration 1:
N = 0;
z = 1;
Vect [1]
Iteration 2:
N = 1;
z = 4;
Vect [1,4]
Iteration 3:
N = 2;
z = 9;
Vect [1,4,9]
etc... ??

 Respuesta aceptada

Geoff Hayes
Geoff Hayes el 20 de En. de 2017
Editada: Geoff Hayes el 20 de En. de 2017
Matthew - try doing the following
y = x;
z = 0*y;
myVector = zeros(N+1,1);
for n = 0:N
z = z+1+2.*n
myVector(n+1) = z;
end
Note how we pre-size the myVector array given that there are N+1 elements. We then just update this array on each iteration of the for loop.

3 comentarios

Geoff Hayes, Thank you so much your example helped me a lot !
Hello Geoff,
I am trying to do something similar but my indexing is not a whole number
for j=3:0.005:7
So, how can I create a vector to save all the single output answers (after each iteration) from my for loop.
In the end my vector (for each variable) wıll be a single column by 800 rows filled with the data that I need Please help.
Thank you very much.
Sara - you could try doing something like
results = zeros(801,1); % since 801 elements in range 3:0.005:7
k = 1;
for j=3:0.005:7
% do some calculation
results(k) = ...; % your result
k = k + 1;
end
Or perhaps
myRange = 3:0.005:7;
myResults = zeros(size(myRange));
for k=1:length(myRange)
j = myRange(k);
% do some calculation with j
results(k) = ...; your result
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 20 de En. de 2017

Comentada:

el 25 de Oct. de 2018

Community Treasure Hunt

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

Start Hunting!

Translated by