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

9 views (last 30 days)
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?

Accepted Answer

Mathieu NOE
Mathieu NOE on 30 Aug 2022
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

More Answers (1)

Steven Lord
Steven Lord on 30 Aug 2022
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

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!