I run the code below and expect to get a uniform histogram. It's not. I don't understand why not.
6 views (last 30 days)
Show older comments
Barbara Margolius
on 30 May 2024
Answered: Barbara Margolius
on 30 May 2024
% I have a two column array, the first column is time and the second column is state. I ran interp1 to observe my data at uniform time points. The results were unexpected. In trying to identify the problem, I have run this simpler code expecting the deterministic uniformly spaced points to be uniformly distributed. They are not. Can anyone explain why not? Thanks.
% Parameters
thismesh = 100; % Number of bins
deltat = 1 / thismesh;
lasttime = 1000; % Example last time
% Generate uniform time steps
xx = 0:deltat:lasttime;
% Calculate fractional times
fractime = (xx - floor(xx)).';
% Plot histogram to check uniformity
figure;
histogram(fractime, thismesh);
title('Histogram of fractional times');
xlabel('Fractional time');
ylabel('Count');
% Display counts in each bin
[counts, edges] = histcounts(fractime, thismesh);
disp('Counts per bin:');
disp(counts);
% Expected count per bin
expected_count = length(fractime) / thismesh;
disp('Expected count per bin:');
disp(expected_count);
% Plot actual counts vs expected uniform count
figure;
bar(counts);
hold on;
yline(expected_count, 'r', 'LineWidth', 2);
hold off;
title('Actual counts vs Expected uniform count');
xlabel('Bin');
ylabel('Count');
legend('Actual counts', 'Expected count');
[SL: formatted code as code and ran that code]
0 Comments
Accepted Answer
the cyclist
on 30 May 2024
It's because of your choice of 100 bins is tuned to the periodicity of your function in a way that makes it the counts chaotic near the bin edges. Here is a better choice for binning, that gives what you expect.
% Parameters
thismesh = 100; % Number of bins
deltat = 1 / thismesh;
lasttime = 1000; % Example last time
% Generate uniform time steps
xx = 0:deltat:lasttime;
% Calculate fractional times
fractime = (xx - floor(xx)).';
%%
% Plot histogram to check uniformity
figure;
histogram(fractime, -0.005 : 0.01 : 1.005);
title('Histogram of fractional times');
xlabel('Fractional time');
ylabel('Count');
0 Comments
More Answers (1)
See Also
Categories
Find more on Histograms 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!