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.

1 view (last 30 days)
the code I'm talking about is cyrcled in red

Answers (2)

William Rose
William Rose on 18 Sep 2022
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 Comment
William Rose
William Rose on 18 Sep 2022
@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).

Sign in to comment.


William Rose
William Rose on 18 Sep 2022
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 Comments

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!