% Sample data - how to create histograms in MatLab:
% Barukyah Shaparenko and John M. Cimbala

clear all
close all

% First, input data

% Method 1: Explicit data values
% x = [1.1;1.2;0.95;1.04;1.06;0.95;0.97;1.03;1.01;...
%    0.94;0.99;1.02;1.03;0.97;1.08;1.11;1.01;0.99]; 

% ---OR---

% Method 2: Import from Excel
% Save Excel data file in same folder as MatLab m-file
% Use xlsread or xlsxread

% sheet_number and data_range are optional
% Default is Sheet 1 with all (numerical) data imported

xls_filename = 'Sample_Excel_histograms.xls';
sheet_number = 1;
data_range = 'B5:B22';
x = xlsread(xls_filename,sheet_number,data_range);

% Direct calculation of statistics:
average = mean(x);
stdev = std(x);


% Built-in MatLab histogram generation package
% # bins = 10
[n1,xout1] = hist(x);
% n = frequency, xout = bin centers
width = 1; % No gaps between bars [Excel: Gap Width = 0]
figure(1)
bar(xout1,n1,width);
title('Automatic Histogram','FontWeight','Bold','FontSize',16)
xlabel('x','FontWeight','Bold')
ylabel('Frequency','FontWeight','Bold')
set(gca,'xgrid','on')
grid


% Specifying the number of bins
% Check Sturgis' rule
J = 1 + 3.3*log10(length(x));
nbins = round(J);
[n2,xout2] = hist(x,nbins);

figure(2)
bar(xout2,n2,width);
title('Histogram w/ Specified Number of Bins','FontWeight','Bold','FontSize',16)
xlabel('x','FontWeight','Bold')
ylabel('Frequency','FontWeight','Bold')
set(gca,'xgrid','on')
grid


% Specifying the bin locations
nbins = 6;
left_edge = 0.90;
bin_width = 0.05;
right_edge = left_edge + nbins*bin_width;
nbins = nbins + 2; % Add bins for x <= left_edge and x > right_edge
bin_centers = [left_edge - 0.5*bin_width:bin_width:right_edge + 0.5*bin_width];
n3 = hist(x,bin_centers);

figure(3)
bar(bin_centers,n3,width)
xmin = left_edge - bin_width;
xmax = right_edge + bin_width;
title('Histogram w/ Specified Number of Bins, Locations','FontWeight','Bold','FontSize',16)
xlabel('x','FontWeight','Bold')
ylabel('Frequency','FontWeight','Bold')
axis([xmin xmax 0 max(n3)+1])
% xlim([xmin xmax])    Use this for setting x axis limits only
set(gca,'xgrid','on')
grid