Coarsening a 2D or 3D grid in Matlab

조회 수: 9 (최근 30일)
Sai Prasanth
Sai Prasanth 2020년 9월 14일
댓글: Sai Prasanth 2020년 9월 17일
Hello,
I have several fields/arrays that are either 2D or 3D. I am looking for a method in which I coarsen the resolution by a factor of 3^2. For example, if I had 699*699 pixels in the old array, I would like to reconstruct that variable such that each pixel in the new array is an average of 3x3 pixels in the old array. What is the best way to do this for 2D as well as 3D arrays?
Thanks.

답변 (1개)

Vinai Datta Thatiparthi
Vinai Datta Thatiparthi 2020년 9월 17일
Hi Sai,
"..each pixel in the new array is an average of 3x3 pixels in the old array.."
Use the conv2 function:
inputData = reshape(1:25,5,5);
kernel = ones(3,3);
outputData = conv2(inputData, kernel, 'valid')
% From your description, I felt it is best to set the shape parameter to 'valid'.
% If this doesn't work for you, explore other shape options ['full' & 'same'] as well.
For N-D matrices, use the nconv function:
inputData3D = reshape(1:125,5,5,5);
kernel = ones(3,3);
outputData3D = convn(inputData3D, kernel, 'valid')
Hope this helps!
  댓글 수: 1
Sai Prasanth
Sai Prasanth 2020년 9월 17일
Thank you, I wrote the following function using convolution to help me coarsen an array of 2 or 3 dimensions (not a 3D convolution but only 2D).
Using this function, say, if W were a 3D array and lat were a 2D array and I want a 3 x 3 moving average, I could simply use:
coarse_W = coarse(W,3);
coarse_LAT = coarse(XLAT,3);
function Z = coarse(X,squaredim)
Y = ones(squaredim,squaredim)/squaredim^2;
if(length(size(X)) == 2)
Z = conv2(X,Y,'same');
elseif (length(size(X)) == 3)
Z = ones(size(X));
for lev = 1:size(X,3) % Works only if the third dimension is vertical levels
Z(:,:,lev) = conv2(squeeze(X(:,:,lev)),Y,'same');
end
end
end

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

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by