Skip to content

Instantly share code, notes, and snippets.

@ekatrukha
Created March 1, 2024 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekatrukha/8a8f336d44b7bef6523fc1acc3c71a19 to your computer and use it in GitHub Desktop.
Save ekatrukha/8a8f336d44b7bef6523fc1acc3c71a19 to your computer and use it in GitHub Desktop.
Matlab calculation of weighted histogram
inputFileName= 'wt chm';
dtin=importdata(strcat(inputFileName,'.csv'));
dBinMin=0;
dBinMax=6;
dBin = 0.1;
%first values then weights
dt=horzcat(dtin(:,2),dtin(:,1));
%something else, get values "without zeros"
dlog=dt(:,1);
for i=1:length(dlog)
if dlog(i)<0.00001
dlog(i)=0.00001;
end
end
%normalize weights to 100
dt(:,2)=dt(:,2)*100/sum(dt(:,2));
dt=sortrows(dt);
%cumulative histogram
cumHistWeighted = horzcat(dt(:,1),cumsum(dt(:,2)));
%weighted pdf histogram
dBinsN=ceil((dBinMax+0.5*dBin-dBinMin)/dBin);
histWeight = zeros(dBinsN,2);
for i=1:dBinsN
histWeight(i,1) = dBinMin+dBin*(i-1);
end
currBin=1;
currMaxBin = dBinMin+0.5*dBin;
for i=1:length(dt(:,1))
val = dt(i,1);
%reached maximum bin, just go on
if currBin ~= dBinsN
%find next bin
if val > currMaxBin
bFoundBin = false;
while ~bFoundBin
currBin = currBin+1;
currMaxBin = currMaxBin + dBin;
if currBin==dBinsN
bFoundBin=true;
else
if val<=currMaxBin
bFoundBin=true;
end
end
end
end
end
histWeight(currBin,2)=histWeight(currBin,2)+dt(i,2);
end
xlswrite(strcat(inputFileName,'_histWeight211.xls'),histWeight);
xlswrite(strcat(inputFileName,'_cumhistWeight211.xls'),cumHistWeighted);
%csvwrite(strcat(inputFileName,'_histWeight.csv'),histWeight);
%csvwrite(strcat(inputFileName,'_cumhistWeight.csv'),cumHistWeighted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment