calculate the averages of non-squared matrix blocks
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (2 件)
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.
0 件のコメント
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)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Performance and Memory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!