How to bin data from a matrix (2D array)

64 ビュー (過去 30 日間)
Tamara del Águila
Tamara del Águila 2021 年 5 月 23 日
コメント済み: Tamara del Águila 2021 年 5 月 24 日
I am trying to downsample a matrix that contains data that sum up to 100 (cdata, it's % data for each pixel) by summing up the % corresponding to each new bin of size npix*npix.
However, I am loosing data for some reason, as it can be somehow seen in the image (and in the title the sum of the binned matrix, you can see how much it sums up, that's never 100%).
The code I have used is below... could anyone help figure out what's the problem?
Else, if there is a more efficient or simpler way of doing it, I'd appreciate it. In the beginning I tried with 'resample' but there is no option of summing up instead of using averages...
xdim = size(cdata,1);
ydim = size(cdata,2);
npix = 10; % number of
n_xbin = ceil(xdim/npix); %ceil to prevent loosing pixels outside the boundaries of the new matrix
n_ybin = ceil(ydim/npix);
cdata2bin = cdata; % original colour data
cdata2bin(xdim:n_xbin*npix+1 , ydim:n_ybin*npix+1) = 0; % fill with zero so the loop cn cover the whole matrix
% build new binned matrix
x = 1;
for xbin = 1:n_xbin
y = 1;
for ybin = 1:n_ybin
databin = cdata(x:x+npix-1, y:y+npix-1);
binned(xbin, ybin) = sum(databin(:));
y = y+npix-1;
end
x = x+npix-1; %skip the bin
end
sum(cdata(:)) % sum up to 100%
sum(binned(:)) %should sum up to 100%... but it does not! (as it can be seen in the image)

採用された回答

Rik
Rik 2021 年 5 月 23 日
If you have the image processing toolbox, you can use blockproc to do the calculation. If you don't mind the overhead, you could also use mat2cell to split your image and use a loop or cellfun to sum elements.
  3 件のコメント
Rik
Rik 2021 年 5 月 24 日
You're welcome. If I solved your question, please consider marking it as accepted answer. If not, feel free to comment with your remaining issues.
Tamara del Águila
Tamara del Águila 2021 年 5 月 24 日
sorry, I didn't know it worked like this... thanks for that piece of information as well!

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

その他の回答 (0 件)

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by