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 (최근 30일)
이전 댓글 표시
the code I'm talking about is cyrcled in red
댓글 수: 0
답변 (2개)
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')
disp(s')
Try the above.
댓글 수: 1
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
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!