Create vector for data after each iteration of a for loop

290 vues (au cours des 30 derniers jours)
Matthew Atilano
Matthew Atilano le 20 Jan 2017
Commenté : Geoff Hayes le 25 Oct 2018
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... ??

Réponse acceptée

Geoff Hayes
Geoff Hayes le 20 Jan 2017
Modifié(e) : Geoff Hayes le 20 Jan 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 commentaires
Sara Fawal
Sara Fawal le 14 Oct 2018
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.
Geoff Hayes
Geoff Hayes le 25 Oct 2018
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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Data Type Identification dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by