Adding values to a matrix in for loop

2 views (last 30 days)
Tony on 5 Dec 2021
Answered: Benjamin on 5 Dec 2021
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.
[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 on 5 Dec 2021
Edited: Star Strider on 5 Dec 2021
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
.
Star Strider on 5 Dec 2021
As always, my pleasure!
.

Benjamin on 5 Dec 2021
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]);