Sum a matrix element using a window size of 4
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Rahul Gulia
il 19 Giu 2023
Commentato: Rahul Gulia
il 21 Giu 2023
Hi everyone,
I am trying to create a matrix(4,2) from a matrix (4,8), by adding 4 elements column wise.
For example:
A = [-2 -2 -2 2 -2 2 -2 -2
-2 2 -2 -2 -2 -2 -2 2
-2 -2 2 -2 -2 2 2 2
-2 2 2 2 -2 -2 2 -2]
should be converted to:
B = [-4 -4
-4 -4
-4 4
4 -4 ]
Looking forward to any kind of suggestion. I was trying a for loop, but that is kind of messy for a large matrix. Hoping to get some simpler solutions by directly using the sum() function. Kindly sugest.
0 Commenti
Risposta accettata
Image Analyst
il 19 Giu 2023
A = [-2 -2 -2 2 -2 2 -2 -2
-2 2 -2 -2 -2 -2 -2 2
-2 -2 2 -2 -2 2 2 2
-2 2 2 2 -2 -2 2 -2]
sumFunction = @(theBlockStructure) sum(theBlockStructure.data(:));
B = blockproc(A, [1, 4], sumFunction)
Più risposte (1)
John D'Errico
il 19 Giu 2023
Modificato: John D'Errico
il 19 Giu 2023
Reshape the array, to be now of size 4x4x2
A = [-2 -2 -2 2 -2 2 -2 -2
-2 2 -2 -2 -2 -2 -2 2
-2 -2 2 -2 -2 2 2 2
-2 2 2 2 -2 -2 2 -2];
Think about the result. What will it look like?
A2 = reshape(A,[4,4,2])
Now, can you sum that new array, along the SECOND dimension? TRY IT!
A2sum = sum(A2,2)
Are you getting close? I hope so. Next, all you need to do is to get rid of that pesky second, singleton dimension. For that, you could use either reshape, or squeeze. TRY IT!
The trick in all of these problems is to understand the sequence in which the elements in your array are stored , and to then visualize what you want in the end. Work towards that goal.
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!