Writing a loop to calculate sums horizontally for ALL rows
4 次查看(过去 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 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!