function [h,div]=HistogramWeighted(samples,weights)

%HistogramWeighted  Represents the weithted histogram
%
%[h,div]=HistogramWeighted(samples,weights)
% samples: values of the samples
% weights: weights of the samples
% h: height of the histogram
% div: division intervals of the histogram

% APRENDIZAJE AUTOMÁTICO (G. Pajares y J. M. de la Cruz, Eds.)
% Editorial: RA-MA
% Capítulo 7 y 8: Monte Carlo I y II
% Autores: Eva Besada-Portas, Sergey M. Plis


%Find the minimum and maximum values of the samples
mins=min(samples);
maxs=max(samples);
%Normalize the weights, just in case they are not normalized.
weights=weights/sum(weights);

%Find the divisions (100)
div=linspace(mins,maxs,100);
step=div(end)-div(end-1);
div=[div(1)-step,div,div(end)+step];

%We are going to represent the height of each element of the histogram.
[sampless,ind]=sort(samples);
weightss=weights(ind);
h=histc(sampless,div); %obtain the number of samples in each division

weigthaux=zeros(1,length(h)); 
k=1;
for i=1:length(h)
    weigthaux(i)=sum(weightss(k:k+h(i)-1)); %Accumulate the weights of the samples in each division
    k=k+h(i);
end

%Final height
h=weigthaux/step; %We divide between step, so the represented total area equals 1

bar(div+step/2,h,1); %We have to add, because in bar, points represent centers. And we have used histc, where points are intervals
colormap(autumn);
 