How to bin data from a matrix (2D array)
24 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tamara del Águila
am 23 Mai 2021
Kommentiert: Tamara del Águila
am 24 Mai 2021
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...
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/627338/image.jpeg)
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)
0 Kommentare
Akzeptierte Antwort
Rik
am 23 Mai 2021
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 Kommentare
Rik
am 24 Mai 2021
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.
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!