Create vector for data after each iteration of a for loop

조회 수: 55 (최근 30일)
Matthew Atilano
Matthew Atilano 2017년 1월 20일
댓글: Geoff Hayes 2018년 10월 25일
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일
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
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개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by