calculate the averages of non-squared matrix blocks
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Antworten (2)
Image Analyst
am 29 Aug. 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 Kommentare
Dyuman Joshi
am 29 Aug. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Performance and Memory finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!