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

回答(1 个)

Star Strider
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by