How do I bin my X and Y data to plot the mean and SD?

조회 수: 6 (최근 30일)
Leeba Ann Chacko
Leeba Ann Chacko 2022년 8월 30일
댓글: Mathieu NOE 2022년 9월 1일
I have 2 variables X and Y
X=[1 2 2 3 4 4 4 2 1 3];
Y=[0.1 0.3 0.31 0.36 0.5 6 6 0.32 0.11 0.38];
I would like to create bins for the X data as follows
[n,bin] = histc(X,linspace(0,5,5))
My bins: 0 1.2500 2.5000 3.7500 5.0000
No. of X values that fall ino above bins : 2 3 1 4 0
Now, I want to place the corrosponding Y values into the X bins
data=full(sparse(1:length(X), bin,Y))
data =
0.1000 0 0 0
0 0.3000 0 0
0 0.3100 0 0
0 0 0 0.3600
0 0 0 0.5000
0 0 0 6.0000
0 0 0 6.0000
0 0.3200 0 0
0.1100 0 0 0
0 0 0.3800 0
Each column represent the bin but I have lost the last bin because none of the values in X belong to that bin and sparse gets rif of the non-zero values.
How can I retain the last column? So that I can measure the mean and std for each column/bin?

채택된 답변

Mathieu NOE
Mathieu NOE 2022년 8월 30일
hello
quick and dirty solution
code should work whatever the "zero" position is in the n array
hope it helps
X=[1 2 2 3 4 4 4 2 1 3];
Y=[0.1 0.3 0.31 0.36 0.5 6 6 0.32 0.11 0.38];
[n,bin] = histc(X,linspace(0,5,5))
data=full(sparse(1:length(X), bin,Y));
% add zero column based on zero(s) output in n array
ind_col_non_zeros = find((n>0)); % col number having non zeros
ind_col_zeros = find((n<1)); % col number having zeros
tmp = zeros(size(data,1),size(data,2)+numel(ind_col_zeros));
tmp(:,ind_col_non_zeros) = data;
data = tmp;
clear tmp

추가 답변 (1개)

Steven Lord
Steven Lord 2022년 8월 30일
X=[1 2 2 3 4 4 4 2 1 3];
Y=[0.1 0.3 0.31 0.36 0.5 6 6 0.32 0.11 0.38];
row = 1:numel(Y);
accumarray([row(:), X(:)], Y)
ans = 10×4
0.1000 0 0 0 0 0.3000 0 0 0 0.3100 0 0 0 0 0.3600 0 0 0 0 0.5000 0 0 0 6.0000 0 0 0 6.0000 0 0.3200 0 0 0.1100 0 0 0 0 0 0.3800 0
  댓글 수: 1
Leeba Ann Chacko
Leeba Ann Chacko 2022년 9월 1일
This one is still missing the last column with just 0 values.

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

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by