MATLAB Answers

Splitapply command and merge results

조회 수: 4(최근 30일)
Ivan Mich
Ivan Mich 2021년 7월 26일
댓글: Rik 2021년 7월 27일
In general I am using this command "splitapply" in order to find mean (average) of a group of data.
edges=1:0.5:10
[N, edges, bin] = histcounts(B, edges);
mean_B=splitapply(@mean, B, bin) %mean
%B is 100x1 double
But I would like to make a code that will :
1) Group my data into bins from edges : 1:0.5:10 (min=1, max=10 with step equal to 0.5)
2) Compute the means of the values in each bin (lets call it set1).
3) Group my data into bins from edges : 2:1:10 (min=2, max=10 with step equal to 1)
4) Compute the means of the values in each bin (set2).
5) Merge two sets of data
Could you please help me in order to make it?
Thanking you in advance

답변(1개)

Rik
Rik 2021년 7월 26일
The question for you is what you mean by merging, but steps 1 to 4 are below.
%generate example data
B=10*rand(1,100);
edges1=[1 0.5 10];
edges2=[2 1 10];
mean_B_set1=mean_group_data(B,edges1)
mean_B_set1 = 1×18
1.1522 1.6931 2.2359 2.7160 3.2395 3.8087 4.3454 4.7591 5.2552 5.7937 6.2050 6.7348 7.2927 7.6282 8.2723 8.7246 9.2756 9.7841
mean_B_set2=mean_group_data(B,edges2)
mean_B_set2 = 1×8
2.5560 3.3270 4.5522 5.6142 6.4405 7.5062 8.4984 9.5299
function mean_B=mean_group_data(B,msm)
B(B<msm(1) | B>msm(3))=[];%remove data outside of bounds
edges=msm(1):msm(2):msm(3);
[~, ~, bin] = histcounts(B, edges);
mean_B=splitapply(@mean, B, bin);
if numel(mean_B)<(numel(edges)-1)
mean_B((end+1):(numel(edges)-1))=NaN;%extend to fill all bins
end
end
  댓글 수: 4
Rik
Rik 2021년 7월 27일
Your desired output will be the third column of the array below.
edges1=[2 1 7 ];
edges2=[2.5 1 6.5];
mean_B_set1=[0.5;1.25;1.6;1.9;3.2];
mean_B_set2=[0.75;1;1.7;2.5];
e1=edges1(1):edges1(2):edges1(3);
e2=edges2(1):edges2(2):edges2(3);
%col 1 contains bin starts, col 2 contains bin ends
%col 3 contains the sets
tmp=[e1(1:(end-1)).' e1(2:end).' mean_B_set1;...
e2(1:(end-1)).' e2(2:end).' mean_B_set2];
output=sortrows(tmp)
output = 9×3
2.0000 3.0000 0.5000 2.5000 3.5000 0.7500 3.0000 4.0000 1.2500 3.5000 4.5000 1.0000 4.0000 5.0000 1.6000 4.5000 5.5000 1.7000 5.0000 6.0000 1.9000 5.5000 6.5000 2.5000 6.0000 7.0000 3.2000

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

Community Treasure Hunt

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

Start Hunting!

Translated by