Writing a loop to calculate sums horizontally for ALL rows
조회 수: 2 (최근 30일)
이전 댓글 표시
I have a matrix that's n-by-12. I have the following loop to calculate the sums for the values of specific cell groups within this array. However, this loop only works for the first row. I'm not sure how to incorporate that it should do this for ALL rows, however many there may be.
Say the array looks like:
row 1: [96, 24, 58, 29, 31, 49, 37, 63, 3, 14, 14, 13]
row 2: [45, 90, 36, 58, 56, 78, 46, 3, 89, 354, 566, 463]
etc.
The number of rows will vary, so that needs to be accounted for. Also happy to make modifications if there is a cleaner way to write the whole thing.
for k = 1:length(a)
c = sum(a(:,1)+a(:,2)+a(:,3));
c(end+1) = sum(a(:,4)+a(:,5)+a(:,6));
c(end+1) = sum(a(:,7)+a(:,8)+a(:,9));
c(end+1) = sum(a(:,10)+a(:,11)+a(:,12));
end
댓글 수: 0
답변 (1개)
Star Strider
2018년 9월 13일
One approach:
n = 7;
A = rand(n, 12); % Create Matrix
cv = sum(A); % Sum Each Column
cm = reshape(cv, 3, []); % Create (3x4) Matrix Of Column Sums
c = sum(cm); % Row Vector Of Desired Column & Row Sums
Experiment to get the result you want.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!