I'm trying to sum every two row and store the answer in new matrix, but the code keep giving me the wrong sum and copy the wrong answer in all the row of the new matrix.

2 ビュー (過去 30 日間)
the code I'm talking about is cyrcled in red

回答 (2 件)

William Rose
William Rose 2022 年 9 月 18 日
Agg_load_1=10*rand(8,1);
N=length(Agg_load_1);
s=zeros(floor(N/2),1); %allocate array for the sums of 2 elements at a time
for i=1:length(s)
s(i)=sum(Agg_load_1(2*i-1:2*i));
end
disp(Agg_load_1')
5.2044 8.8178 8.3728 4.5701 3.4480 4.6383 4.2776 3.3500
disp(s')
14.0222 12.9429 8.0862 7.6275
Try the above.
  1 件のコメント
William Rose
William Rose 2022 年 9 月 18 日
@ibrahim nathem, If Agg_load_1 has an odd number of elements, the code above works without error. It rounds down when it allocates vector s. So if Agg_load_1 has 9 elements, s will have 4 elements and will not include a sum for Agg_load_1(9).

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


William Rose
William Rose 2022 年 9 月 18 日
Agg_load_1=10*rand(8,1);
N=length(Agg_load_1);
s=Agg_load_1(1:2:end-1)+Agg_load_1(2:2:end);
disp(Agg_load_1'); disp(s')
The approach above is nicer than my first answer, because it does not use a for loop. It works when Agg_load_1 has an even number of elements. It would need an adjustment if Agg_load_1 has an odd number of elements.
  3 件のコメント

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by