function [diffMax, C] = compareAny(A,B)
% COMPAREANY - calcul relative difference between two objects, element by element
%
% Syntax :
% [diffMax, C] = compareAny(A,B)
%
% Inputs :
% A - structure, cell array, number, logical or string
% B - structure, cell array, number, logical or string, same class as A
%
% Outputs :
% DIFFMAX - the maximal relative difference between A and B
% C - same class as A and B, holding 0 if element of A and element of B are equals ;
% otherwise, relative difference (for different character, it is always 1)
%
% Examples:
% >> a = {'bla',1,[1,31]};
% >> b = {'blo',1,[1,25]};
% >> [diffMax, C] = compareAny(a,b)
% diffMax =
% 0.1935
% C =
% [1] [0] [1x2 double]
%
% >> C{1,3}
% ans =
% 0 0.1935
%
% Other m-files required: none
% Subfunctions: ANYTRUE
% MAT-files required: none
%
% See also: COMPARE, by Dario (Matlab Central)
%
% Author: Ygal
% Last revision: 02/19/09
% Created with Matlab version: 7.6.0.324 (R2008a)
%%
diffMax = 0;
if strcmp(class(A),class(B));
if isstruct(A)
Afields = fieldnames(A);
Bfields = fieldnames(B);
if ~anytrue(compareAny(Afields,Bfields))
for i=1:size(Afields,1)
field = Afields{i};
eval(['[C.',field,', diffMax2]= compareAny(A.',field,',B.',field,');']);
diffMax = max(max(diffMax2));
end
else
error('Structs must have the same fields.');
end
elseif iscell(A)
if size(A)==size(B)
[C , diffMax2] = cellfun(@(a,b) compareAny(a,b),A,B,'UniformOutput',false);
diffMax = max(max((cell2mat(diffMax2))));
else
error('Cell arrays must have the same size.');
end
elseif isnumeric(A) || islogical(A)
if size(A)==size(B)
C = abs(A-B)./A; % Relative difference
diffMax = max(max(diffMax, C));
else
error('Numeric and logical arrays must have the same size.');
end
elseif ischar(A)
C = ~strcmp(A,B);
diffMax = max(max(diffMax, C));
else
error('A and B are of an unknown type. Valid types are: struct, cell, numeric and logical arrays and strings.');
end
else
error('A and B must be of the same type.');
end
function o = anytrue(A)
% ANYTRUE(A) outputs 0 if the A object hold only zeros ; otherwise
% (if at least on element of A is non-zero), it ouputs 1
% (this function anytrue extends the builtin function any for all classes)
if isstruct(A)
o = anytrue(struct2cell(A));
elseif iscell(A)
o = anytrue(cellfun(@(a) anytrue(a),A));
elseif isnumeric(A) || islogical(A)
if ~isscalar(A)
o = anytrue(any(A));
else
o = any(A);
end
elseif ischar(A)
o = any(~strcmp(A,''));
else
error('A is of an unknown type. Valid types are: struct, cell, numeric and logical arrays and strings.');
end