calculate the averages of non-squared matrix blocks

2 visualizaciones (últimos 30 días)
LH
LH el 29 de Ag. de 2023
Respondida: Dyuman Joshi el 29 de Ag. de 2023
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:
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.

Respuestas (2)

Image Analyst
Image Analyst el 29 de Ag. de 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.
ave_A = 1×3
0.9375 1.1875 1.2500

Dyuman Joshi
Dyuman Joshi el 29 de Ag. de 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)
ans = 3×1
0.9375 1.1875 1.2500

Categorías

Más información sobre Performance and Memory 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!

Translated by