Adding values to a matrix in for loop

조회 수: 40 (최근 30일)
Tony
Tony 2021년 12월 5일
답변: Voss 2021년 12월 5일
I have a matrix, "in", with a set of values. I want to create a new array, starting at 29, and continuosly adding the next value of array "in" to the new array.
So I start with 29, and add "in". The final matrix should be:
[29 37 45 53 61]
however, I am getting this:
[37 37 37 37 45 45 45 45 53 53 53 53 61 61 61 61]
It's duplicating each value by 4 (the length of the matrix).
Here's my code:
in = [8 8 8 8];
values = [];
values_change=29;
for i=1:length(in)
values_change = values_change +in;
values = [values, values_change];
end
disp(values)
How do I fix this? Thanks!
NOTE: the matrix in may change so it might not all be values of 8. So I need the code to account this matrix, not the values, 8.

채택된 답변

Star Strider
Star Strider 2021년 12월 5일
편집: Star Strider 2021년 12월 5일
Subscript ‘in’ here —
values_change = values_change + in(i);
and then subscript ‘values’ (the preallocation is optional, however a good habit to adopt, sinc it produces much more efficnet matrix operations in this snd similar applications). See if that produces the desired result.
in = [8 8 8 8];
values = NaN(1,numel(in)+1);
values_change = 29;
values(1) = values_change;
for i=1:length(in)
values_change = values_change + in(i);
values(i+1) = values_change;
end
disp(values)
29 37 45 53 61
.
  댓글 수: 2
Tony
Tony 2021년 12월 5일
Thank you so much!!! This worked.
Star Strider
Star Strider 2021년 12월 5일
As always, my pleasure!
.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Voss
Voss 2021년 12월 5일
Each time through the loop, the code is concatenating the vector values_change onto the end of the vector values. (Note that the code inside the loop doesn't depend on the loop iterator i.) To append only one element at a time to the vector values, you can do this:
in = [8 8 8 8];
values = [];
values_change=29;
for i=1:length(in)
values_change = values_change +in(i);
values = [values, values_change];
end
However, the value of values at the end of this wil not include the initial value of values_change (i.e., 29) because it is incremented before it is stored in values the first time. To correct that, you can initialize values to have the value 29 before the loop:
in = [8 8 8 8];
values_change=29;
values = values_change;
for i=1:length(in)
values_change = values_change +in(i);
values = [values, values_change];
end
This will give you the desired output.
However, since this loop is essentially doing a cumulative sum over in, you can do the same thing without a loop, using the cumsum function:
in = [8 8 8 8];
values_change = 29;
values = values_change+cumsum([0 in]);

카테고리

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