IRootLab
An Open-Source MATLAB toolbox for vibrational biospectroscopy
percs2no_unitss.m
Go to the documentation of this file.
1 %> @ingroup conversion maths
2 %>@file
3 %>@brief Converts percents to number of units with extra care
4 %>
5 %> Extra care is taken so that:
6 %> @arg no elements in output be zero
7 %> @arg sum of elements in output does not surpass "total"
8 %
9 %> @param percs
10 %> @param total
11 %> @return no_unitss
12 function no_unitss = percs2no_unitss(percs, total)
13 if sum(percs) > 1
14  irerror('Sum of percentages must be <= 1!');
15 end;
16 if find(percs <= 0)
17  irerror('All percentages must be a positive non-zero!');
18 end;
19 
20 np = length(percs);
21 no_unitss = zeros(1, np);
22 
23 % The strategy is to start giving units to the smallest percentages first
24 [vals, idxs] = sort(percs);
25 for i = 1:np
26  if i < np
27  no_unitss(idxs(i)) = max(1, round(vals(i)*total)); % Care 1
28  else
29  sofar = sum(no_unitss);
30  temp = max(1, round(vals(i)*total)); % Care 1
31  if sofar+temp > total
32  % Care 2: If would blow, the guy due to receive the most will actually get the remainder
33  temp = total-sofar;
34  if temp <= 0
35  irerror('Number of units =%d is too small to split!', total);
36  end;
37  no_unitss(idxs(i)) = temp;
38  else
39  no_unitss(idxs(i)) = temp;
40  end;
41  end;
42 end;
function irerror(in s)
function percs2no_unitss(in percs, in total)