Calculate the average of a matrix

조회 수: 11 (최근 30일)
LH
LH 2023년 6월 29일
답변: Rik 2023년 6월 29일
Hi,
I have a square matrix with dimension . I want to take average of all elements inside each block that includes 4 horizontal and 4 vertical points of the matrix, as shown below. This means, the caluclations happenes 380 times, and hence the final averged matrix should have a dimension of .
This is my code.
size(G,1) = 1520;
subs = (size(G,1)/4); %number of blocks
ObsPoints = 4; %number of points in each block
G_sam = zeros(subs,subs); %initialise the averaged sampled G matrix
%calculate the averages
for icell = 1:subs
for obs_hor = (ObsPoints*(icell-1))+1:(ObsPoints)*(icell)
for obs_ver = (ObsPoints*(icell-1))+1:(ObsPoints)*(icell)
G_sam = sum(sum(G(obs_hor,obs_ver)))/(ObsPoints);
end
end
end
I am not sure if my code is on the right track, but any help would be appreicted.
Thanks.

채택된 답변

Mihir
Mihir 2023년 6월 29일
Hi Lama, your code is on the right track, but there are a couple of issues that need to be addressed. Here's an updated version of your code that should work correctly:
size_G = size(G, 1);
Unrecognized function or variable 'G'.
subs = size_G / 4; % number of blocks
ObsPoints = 4; % number of points in each block
G_sam = zeros(subs); % initialize the averaged sampled G matrix
% calculate the averages
for icell = 1:subs
obs_hor_start = (ObsPoints * (icell - 1)) + 1;
obs_hor_end = ObsPoints * icell;
for obs_hor = obs_hor_start:obs_hor_end
obs_ver_start = (ObsPoints * (icell - 1)) + 1;
obs_ver_end = ObsPoints * icell;
for obs_ver = obs_ver_start:obs_ver_end
G_sam(icell) = G_sam(icell) + G(obs_hor, obs_ver);
end
end
G_sam(icell) = G_sam(icell) / (ObsPoints * ObsPoints);
end
In the updated code, I made the following changes:
  1. Corrected the size of the G_sam matrix to subs instead of subs x subs, as the resulting matrix should have dimensions subs x subs.
  2. Used separate variables (obs_hor_start, obs_hor_end, obs_ver_start, obs_ver_end) to define the range of indices for each block.
  3. Accumulated the values of G(obs_hor, obs_ver) in G_sam(icell) instead of overwriting it in each iteration.
  4. Divided G_sam(icell) by (ObsPoints * ObsPoints) after the innermost loop to calculate the average.
After running this updated code, the G_sam matrix will contain the averaged values for each block.

추가 답변 (2개)

Arya Chandan Reddy
Arya Chandan Reddy 2023년 6월 29일
편집: Arya Chandan Reddy 2023년 6월 29일
Hi Lama, I understand that you want to calculate average of elements grouped 4-by-4. Here is one way you can do this with shorter piece of code.
a =rand(1520,1520);
p =ones(380,1)*4;
x =mat2cell(a, p , p);
mean4x4 = cellfun(@(r) mean(r,'all') , x);
Here,
In line 3 mat2cell groups the matrix into cells of size 4x4 as desired.
In line 4 cellfun performs the average operation on each of the cells.
Refer the documentation to understand it better.
In the above code replace 'a' with your matrix to replicate it on your end.
Hope it helps.
  댓글 수: 1
Rik
Rik 2023년 6월 29일
You should be aware that hiding the loop in cellfun reduces the performance of the code. It may result in shorter code, but is a bad habit. One exception is the legacy syntax (i.e. cellfun('isempty',___) is faster than a loop).

댓글을 달려면 로그인하십시오.


Rik
Rik 2023년 6월 29일
Apart from the other solutions provided there are two other solutions you could give a go. Let's try this with a smaller example (with block sizes of 2 by 2).
If you have the Image Processing Toolbox you can use blockproc:
G=[ 1 2 10 20;
3 4 30 40;
5 6 50 60;
7 8 70 80];
G_sam1 = blockproc(G,[2 2],@(x)sum(x.data,'all'))
G_sam1 = 2×2
10 100 26 260
If you don't, you can use a convolution. That is a bit tricky to adapt to different sizes, since you need to make sure the kernel has odd sizes. Easy enough to do, but you need to keep it in mind.
tmp = convn(G,[0 0 0;0 1 1;0 1 1],'same');
G_sam2 = tmp(2:2:end,2:2:end)
G_sam2 = 2×2
10 100 26 260

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by