Creating histogram without using built in function

조회 수: 38 (최근 30일)
David Fariyike
David Fariyike 2022년 1월 28일
편집: Voss 2022년 1월 29일
I am trying to create a code that mimics the hist() function but I am running into an issue on the final bin.
Here is what I have:
Pie=sin(2*pi*tt); %array of data p=sin(2*pi*t/T)
L=10; %number of bins
minPie = min(Pie); %min value of array
maxPie = max(Pie); %max value of array
binwidth = (maxPie - minPie)/L; %width of bin
binnum = 1+floor((Pie - minPie) / binwidth); %value of array to a bin
bincounts = accumarray(binnum(:), 1); %amount to each bin
X = minPie + (0:L) * binwidth; %X of histogram
figure (1)
bar(X, bincounts) %my histogram
figure (2)
hist(Pie,10) %matlab histogram
My code returns this figure which has 11 bins at a bin width of 0.2.
Matlab's hist function returns this figure which has 10 bins with a bin width of 0.2.
How can I change my last bin so that the two figures are identical?
  댓글 수: 1
David Fariyike
David Fariyike 2022년 1월 28일
tt on the sin function is just equal spaced intervals (linspace) from an initial to a final time.

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

채택된 답변

Voss
Voss 2022년 1월 28일
편집: Voss 2022년 1월 29일
You're going to run into edge effects like that, due to the nature of floating-point arithmetic. You can just fix values out of bounds after calculating them.
tt = linspace(0,10,100);
Pie=sin(2*pi*tt); %array of data p=sin(2*pi*t/T)
L=10; %number of bins
minPie = min(Pie); %min value of array
maxPie = max(Pie); %max value of array
binwidth = (maxPie - minPie)/L; %width of bin
binnum = 1+floor((Pie - minPie) / binwidth); %value of array to a bin
binnum(binnum < 1) = 1; % correct the edge effects
binnum(binnum > L) = L;
% bincounts = accumarray(binnum(:), 1); %amount to each bin
bincounts = zeros(1,L);
for ii = 1:L
bincounts(ii) = nnz(binnum == ii);
end
% use the bin centers for plotting:
X = minPie + (0.5:L-0.5) * binwidth; %X of histogram
figure (1)
bar(X, bincounts) %my histogram
figure (2)
hist(Pie,L) %matlab histogram

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Histograms에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by