calculate the averages of non-squared matrix blocks

조회 수: 4 (최근 30일)
LH
LH 2023년 8월 29일
답변: Dyuman Joshi 2023년 8월 29일
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.

답변 (2개)

Image Analyst
Image Analyst 2023년 8월 29일
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 2023년 8월 29일
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

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by