Writing a loop to calculate sums horizontally for ALL rows
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Star Strider
el 13 de Sept. de 2018
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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!