MATLAB: Binning data into a new matrix

binning

I have a three column matrix which consists of three columns (x,y,z) as shown below:
I would like to bin the data in column Y but instead of puting the count in a new column i.e bins, I would like to put the the corresponding value in column Z. For example, I would like to bin the value in column Y (-2.5 in blue cell), but instead of putting the count in bins, I would like to put the value in colum Z (12 in red cell) in that bin.
I have written the code below but its putting the count only:
yy = my_matrix(:,2) % taking the second column
% binning
edges = -2.5:0.3:2.5;
N = histcounts(yy,edges);
new_matrix(:,i)= N;
How can I improve it?

Best Answer

Your code is returning counts only because you are only requesting the first output of histcounts
yy = my_matrix(:,2); % taking the second column
zz = my_matrix(:,3); % according to the diagram
% binning
edges = -2.5:0.3:2.5;
[N,~,bin] = histcounts(yy,edges);
% match the values of zz to the bins that elements
% of yy went into.
%% EDIT %%
zz_in_bins = cell(size(N));
u = unique(bin); % To avoid dealing with empty bins
binIndex = reshape(u,1,numel(u));
for idx = binIndex
zz_in_bins{idx} = zz(bin==idx);
end