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... ??

 採用された回答

Geoff Hayes
Geoff Hayes 2017 年 1 月 20 日
編集済み: Geoff Hayes 2017 年 1 月 20 日

7 投票

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 件のコメント

Rasik Michailov
Rasik Michailov 2018 年 5 月 14 日
Geoff Hayes, Thank you so much your example helped me a lot !
Sara Fawal
Sara Fawal 2018 年 10 月 14 日
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 2018 年 10 月 25 日
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

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by