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