Calculate the average of a matrix
Ältere Kommentare anzeigen
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.
Akzeptierte Antwort
Weitere Antworten (2)
Arya Chandan Reddy
am 29 Jun. 2023
Bearbeitet: Arya Chandan Reddy
am 29 Jun. 2023
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,
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 Kommentar
Rik
am 29 Jun. 2023
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).
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'))
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)
Kategorien
Mehr zu Neighborhood and Block Processing finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!