function [varargout] = rectify(varargin)
% rectify is used to ensure that a set of matrices have identical
% dimensions by reproducing those matrices with replications along
% singleton dimensions. For example, the command
%
% [A, B] = rectify(a,b)
%
% If a was 1x2x1, and b was 3x1x4, both A and B would be 3x2x4 matrices. A
% would be the original two-element row vector duplicated for three rows,
% and that matrix duplicated for four levels. Similarly, B will be a
% version of b replicated to have two columns. If a had been 1x2x2, output
% would still be produced, but if a had been 1x2x3, an error would be
% returned since 3 is not a whole number factor of 4.
%
% This function will work for arbitary dimensions, so long as for each
% dimension all matrices have either one element, an integer factor of the
% maximum number of elements, or the same number of elements (i.e. there is
% a clear way to extrapolate).
%
% Written by J.A. Dunne, 2005
%
for i=1:nargin
dim = size(varargin{i});
if i==1
dims = dim;
else
dims = [[dims ones(size(dims,1),length(dim)-size(dims,2))] ; [dim ones(1,size(dims,2)-length(dim))]];
end
end
outdims = max(dims,[],1);
warning off
repeatnum = repmat(outdims,size(dims,1),1)./dims;
if ~isequal(repeatnum,round(repeatnum)) || any(isinf(repeatnum(:)))
error('Incompatible dimensions');
end
for i=1:nargin
varargout{i} = repmat(varargin{i},repeatnum(i,:));
end