MATLAB: Bin data and fit curve

histogram

Hi, I have the following data:
– A vector of physical stimulus properties, something like: [0.8, 0.7, 0.56,0.4,….,0.01]
– For each of the vector's elements, the response of the subject (either "0" or "1").
What I want: I want to bin the data with the physical stimuli, and determine the percentage of "1"s responded for this bin (it would be the percentage of correct answers for the bin).
Additionally, I want a curve fittet through these percentages. I know about the hist function, but I am not sure of how I can apply it here. Thanks

Best Answer

binedges = 0 : 0.1 : 1; %set as appropriate

[~, ~, binnumber] = histcounts( StimulusVector, binedges );
maxbin = max(binnumber);
count0 = accumarray(binnumber, Response == '0', [1 maxbin]);
count1 = accumarray(binnumber, Response == '1', [1 maxbin]);
total_for_bins = count0 + count1;
percent_per_bin = count1 ./ max(1,total_for_bins) * 100;
If you only need the percentages and not the counts, you can make this a bit shorter:
binedges = 0 : 0.1 : 1; %set as appropriate
[~, ~, binnumber] = histcounts( StimulusVector, binedges );
percent_per_bin = accumarray(binnumber, Response == '1', [], @mean) * 100;
To fit a curve:
x = (binedges(1:end-1) + binedges(2:end))/2;
y = percent_per_bin;
and now you can fit your curve on x and y using whatever distribution seems suitable. You might want to look inside histfit() to see how it does the fitting and plotting.