Search code examples
matlabgroupingmatlab-figurebinning

Binning Values from 2 variables using the same mean for each bin


How do I bin data from two different groups into bins centered around the same value?

As a toy example,

A(:,1) = [0.05:0.05:0.80]';
A(:,2) = [ones(7,1); [0.6; 0.6; 0.4]; zeros(6,1)];
B(:,1) = [0.15:0.1:0.95]';
B(:,2) = [ones(4,1); [0.8; 0.8; 0.2]; zeros(2,1)];
plot(A(:,1),A(:,2)); hold on; plot(B(:,1),B(:,2));

I'd like to bin and plot A and B on the same plot, but with the data binned at points 0.2, 0.4, 0.6, and 0.8 on the X-Axis for both A and B, meaning that there'll be uneven data in each bin. How should I go about group these values with a mean centered around those points?


Solution

  • Your request is a little bit unclear, but reading through the lines and your comment, I think this is what you were looking for:

    edges = [0.2 0.4 0.6 1];
    
    A(:,1) = (0.05:0.05:0.80).';
    A(:,2) = [ones(7,1); [0.6; 0.6; 0.4]; zeros(6,1)];
    [~,A_bins] = histc(A(:,1),edges);
    [A_bin_vals,~,A_idx] = unique(A_bins);
    A_avg = accumarray(A_idx,A(:,2),[numel(A_bin_vals) 1],@mean) ;
    
    B(:,1) = (0.15:0.1:0.95).';
    B(:,2) = [ones(4,1); [0.8; 0.8; 0.2]; zeros(2,1)];
    [~,B_bins] = histc(B(:,1),edges);
    [B_bin_vals,~,B_idx] = unique(B_bins);
    B_avg = accumarray(B_idx,B(:,2),[numel(B_bin_vals) 1],@mean) ;
    
    plot(0:3,A_avg,'-.r*'),hold on,plot(0:3,B_avg,'-.b*'),hold off;
    xticks(0:3);
    xticklabels({'0.2' '0.4' '0.6' '0.8'});
    

    Output:

    Result

    Actually, in order to accomplish this, I discretized the first column of your matrix applying the desired edges using histc. Then, using the accumarray function, I applied the mean function to all the value of the second column grouped by bin.