Code covered by the BSD License  

Highlights from
moneysplit

from moneysplit by John T. McCarthy
Divide a sum of money in a certain ratio, making sure that the amounts add up exactly to the total.

moneysplit(x,ratio)
function y = moneysplit(x,ratio)

%MONEYSPLIT Divides a sum of money in a certain ratio
%
% SYNTAX: y = moneysplit(x,ratio)
%
% SAMPLE: y = moneysplit(3679.02,[100 100 200])
%
% --->    [919.75 919.76 1839.51]
%
% PURPOSE: When sums of money are divided, and when the dividend amounts
%          have been rounded to the nearest cent, they may not add up
% exactly to the total. It is then necessary to look at further decimal
% places, in order to find 'the best candidates' to change.
%
% This function performs the task, and makes sure that the smaller amounts
% add up exactly to the total. This is no 'rocket science' program, but it
% can be of use in filling in expense accounts, and also in the subdivision
% of share-lots for a tax return.

before_rounding = [x * ratio/sum(ratio)]';
y = round(100 * before_rounding)/100; % rounded version
yy = before_rounding - y; % differences

if sum(y) < x % adjusting amounts upwards
iterations = round((x-sum(y))/.01);
[m,i] = sort(yy,1,'descend');
   for j = 1:iterations
    y(i(j)) = y(i(j))+0.01; 
   end
end

if sum(y) > x % adjusting amounts downwards
iterations = round((sum(y)-x)/.01);
[m,i] = sort(yy,1,'ascend');
   for j = 1:iterations
    y(i(j)) = y(i(j))-0.01;
   end
end

format long g
before_rounding
format bank
sum_of_splits = sum(y)

Contact us at files@mathworks.com