Summing every nth column
Mostrar comentarios más antiguos
Hi,
I have a 1336 by 89700 matrix. I want to sum every 300th colum starting from the first column so that I end up with a 1336 by 300 matrix. So the first colum in the new matrix will be the sum of colum 1, 300, 599....etc. of the previous matrix. And the second column of the new matrix will be the sum of column 2, 301, 600...etc. of the previous matrix. I hope I was able to clearly explain what I want. Any help will be appreciated.
Respuesta aceptada
Más respuestas (2)
Yongjian Feng
el 29 de Nov. de 2021
Your logic is not consistent. from 1 to 300, there are 298 rows in between. But from 300 to 600, there are 299 rows in between.
You might want 1, 301, 601, etc?
You can use reshape and sum to do this. Here a simpler example of summing 1, 4th, 7th.
ma = [1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15; 16 17 18;19 20 21; 22 23 24; 25 26 27]
mb = reshape(ma', 9, 3)
mc = sum(mb, 2)
me = reshape(mc, 3, 3)'
ma =
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24
25 26 27
mb =
1 10 19
2 11 20
3 12 21
4 13 22
5 14 23
6 15 24
7 16 25
8 17 26
9 18 27
mc =
30
33
36
39
42
45
48
51
54
me =
30 33 36
39 42 45
48 51 54
1 comentario
Adnan Habib
el 29 de Nov. de 2021
Image Analyst
el 29 de Nov. de 2021
I think this does what you said, though I'm not sure it's what you want:
data = rand(1336, 89700); % Create sample data.
means = zeros(1, 299); % Preallocate.
for col = 1 : 299
% Extract every 300th column, starting with column "col", into a new matrix.
extractedMatrix = data(:, col : 300 : end); % A new matrix 1/300th as wide as the original
% Sum all the values in that matrix, and put that sum into means.
means(col) = sum(extractedMatrix(:)); % Get a single sum from the entire 2-D matrix.
end
2 comentarios
Adnan Habib
el 29 de Nov. de 2021
Image Analyst
el 29 de Nov. de 2021
OK, let's examine this. So your original matrix is 1336 rows tall by 89700 columns wide. So if you take every 299'th column (1, 300, 599, etc.) you get an extracted matrix of 1336 rows tall by 299 columns wide.
So now you say "So the first colum in the new matrix will be the sum of colum 1, 300, 599....etc. of the previous matrix." so we're to sum the extracted matrix row-by-row over all the columns so we'd end up with a new matrix of 1336 by 1 for the sum over the columns. So we'd do sums = sum(extractedMatrix, 2).
See my other answer elsewhere on the page for a full solution.
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!