Binning regions of a 2D matrix slices (and extending this into the third dimension)

9 ビュー (過去 30 日間)
Hello,
I am having an issue binning regions of a 3D matrix (but I want the binning to occur in the X-Y dimension for each Z slice). Let's say I have a matrix of 512x128x1200, each 2D slice has dimension 512x128, but say I want to bin the pixel counts such that we create a 2D sliced 32x32 matrix (each element being the sum of 16x4 regions within the original larger matrix, is this possible? Then if we can perform this binning in 2D I want to extend this to each element in the Z-direction
It also would be nice then in future to have control of the X/Y bin 'width' so that the matrix can be reshaped into other square orientations, I have just chosen 32x32 as an arbritary starting point!
Hopefully that makes sense!
Cheers

採用された回答

Bruno Luong
Bruno Luong 2020 年 8 月 14 日
編集済み: Bruno Luong 2020 年 8 月 14 日
This assumes the first/second dimensions of your matrix are divisible by 32
% Test matrix
A=rand(512,128,1200);
binsz = 32;
[m,n,p] = size(A);
mr = m/binsz;
nr = n/binsz;
B = reshape(A,mr,binsz,nr,binsz,p);
B = sum(B,[1 3]);
B = reshape(B,binsz,binsz,p);
  3 件のコメント
Bruno Luong
Bruno Luong 2020 年 8 月 14 日
編集済み: Bruno Luong 2020 年 8 月 14 日
See argument 'omitnan'of SUM.
Alternatively you can replace NaN by 0
B(isnan(B))=0
before the sum
Matt J
Matt J 2020 年 8 月 14 日
Bruno's technique is pre-implemented for you in sepblockfun
B=sepblockfun(A,[16,4,1],@(x,d) sum(x,d,'omitnan'))

サインインしてコメントする。

その他の回答 (1 件)

Alan Moses
Alan Moses 2020 年 8 月 14 日
Hi Eunan,
You can use the convn function to help you achieve this. Please look at the below example where I have taken ‘X’ as the large matrix and reshaped it into a smaller matrix ‘Z’:
X = 2*ones(512,128,3);
x_width = 16;
y_width = 4;
Y = convn(X,ones(x_width,y_width),'valid');
Z = Y(1:x_width:end,1:y_width:end,:); %Z dimensions – 32x32x3
Hope this helps!
  1 件のコメント
Eunan McShane
Eunan McShane 2020 年 8 月 14 日
Thank you! This does work, however (I should have said) there is a portion of the data which is NaN and so I want to ignore these entries in the sum, the other answer allows me to use nansum to this end!
Cheers though this is a really useful function which I can use for other applications!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by