Binning data into a new matrix

조회 수: 25 (최근 30일)
Allan Miller
Allan Miller 2020년 1월 6일
댓글: Max Murphy 2020년 1월 13일
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?
  댓글 수: 3
Allan Miller
Allan Miller 2020년 1월 6일
Thanks Guillaume,
So I would like to put an array of values which have a value of 12 in the ith bin and zero elsewhere. i.e, for that example, I would like to put a value of 12 in the bin corresponding to -2.2 : -2.5 and put zeros in other bins from -2.1 : 2.5
Guillaume
Guillaume 2020년 1월 6일
편집: Guillaume 2020년 1월 6일
Sorry, I don't understand. Here is a simple exampl, given:
% Y Z
M = [-2.5 12
-2.4 15
-2.3 -1
-2.2 5
-2.1 10]
and
edges = [-2.5 -2.2 -1.9];
What exact output do you want?
result = ????
Please write it out as a cell array or matrix.

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

채택된 답변

Max Murphy
Max Murphy 2020년 1월 6일
편집: Max Murphy 2020년 1월 6일
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
  댓글 수: 7
Guillaume
Guillaume 2020년 1월 13일
I think we understood that. The problems come when you have several X that falls into the same bin. Which of the matching Y values goes into the bin? You never answered my question so we don't know.
If there is only ever one X and Y per bin, then you're not actually doing any binning and there are much simplers ways to achieve what you want.
Max Murphy
Max Murphy 2020년 1월 13일
Indeed, if there is one X and Y per bin, I would not follow the code that I've posted above, and instead use discretize as suggested by Guillaume and Steven elsewhere in this thread.

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

추가 답변 (1개)

Steven Lord
Steven Lord 2020년 1월 6일
Use the discretize function. See the "Assign Bin Values" example on that documentation page as I believe it does what you're trying to do.

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by