calculate the averages of non-squared matrix blocks
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have a non-squared matrix with a dimension of
and I would like to calculate the averages of each
block so I can get a
average vector. A schematic explanation is shown below:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1467381/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1467386/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1467391/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1467396/image.png)
The matrix and the attempt I have is the following:
close all;
clear all;
%define the 12x4 matrix
A = [1 0 2 0;
0 1 3 0 ;
1 1 0 0 ;
0 2 3 1 ;
3 2 3 0 ;
0 1 1 2 ;
3 1 0 2 ;
0 0 1 0 ;
2 1 3 1 ;
3 2 0 0 ;
0 0 2 0 ;
1 3 0 2];
%calculate the average of A for each 4x4 block
Points = 4;
for irow = 1:Points:size(A,1)
for icol = 1:size(A,2)
block_sum = 0;
block_sum = block_sum + A(irow, icol);
end
end
block_avg = block_sum / Points;
block_row = ceil(irow / Points);
block_col = ceil(icol / Points);
ave_A(block_row, block_col) = block_avg;
Any help would be appreciated. Thanks.
0 commentaires
Réponses (2)
Image Analyst
le 29 Août 2023
Here is one way (there are others):
% Define the 12x4 matrix
A = [1 0 2 0;
0 1 3 0 ;
1 1 0 0 ;
0 2 3 1 ;
3 2 3 0 ;
0 1 1 2 ;
3 1 0 2 ;
0 0 1 0 ;
2 1 3 1 ;
3 2 0 0 ;
0 0 2 0 ;
1 3 0 2];
%calculate the average of A for each 4x4 block
Points = 4;
index = 1;
for iRow = 1:Points:size(A,1)
ave_A(index) = mean(A(iRow:iRow+Points-1, :), 'all');
index = index + 1;
end
ave_A % Display in command window.
0 commentaires
Dyuman Joshi
le 29 Août 2023
A = [1 0 2 0;
0 1 3 0 ;
1 1 0 0 ;
0 2 3 1 ;
3 2 3 0 ;
0 1 1 2 ;
3 1 0 2 ;
0 0 1 0 ;
2 1 3 1 ;
3 2 0 0 ;
0 0 2 0 ;
1 3 0 2];
%nxn block
n=4;
%Use conv2 to get mean of every nxn block of input array
B = conv2(A,ones(n),'valid')/n^2;
%Select every nth element
out = B(1:n:end)
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!