Adding values to a matrix in for loop

39 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by