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 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
the code I'm talking about is cyrcled in red
0 Commenti
Risposte (2)
William Rose
il 18 Set 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')
disp(s')
Try the above.
1 Commento
William Rose
il 18 Set 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).
William Rose
il 18 Set 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.
Vedere anche
Categorie
Scopri di più su Characters and Strings in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!