How do I bin my X and Y data to plot the mean and SD?
7 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
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
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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Line Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!