function C = compare(A,B)
% COMPARE(A,B) compares A and B element-by-element
% A and B must be of the same type, and of one of the following types:
% struct, cell array, numeric or logical array or string.
% A and B may contain further elements of the types listed above (if they
% are cell arrays or structs).
% If A and B are structs, and/or contain structs, all structs the must have
% the the same fields.
% If A and B are arrays, and/or contain arrays, all arrays must be of the
% same size.
% Strings don't need to be of the same length.
% The return value C is of the same type as A and B, and contains the same
% elements as A and B, but C contains only logical values, in place of any
% numeric values and strings in A and B.
% If a number or string in A equals the number (resp. string) in B, C has a
% logical 1 in the same place as the number (resp. string). Otherwise C has
% a logical 0 in this place.
% HINT:
% use alltrue(compare(a,b)) to check if a and b are identical
% EXAMPLE 1:
% >> a = {'a',1,[1,1]};
% >> b = {'a',1,[1,2]};
% >> a == b
% ??? Undefined function or method 'eq' for input arguments of type 'cell'.
% >> compare(a,b)
% ans =
% [1] [1] [1x2 logical]
% >> ans{1,3}
% ans =
% 1 0
% EXAMPLE 2:
% >> a.f1 = 'foo';
% >> a.f2 = 'bar';
% >> b.f1 = 'foo';
% >> b.f2 = 'rab';
% >> compare(a,b)
% ans =
% f1: 1
% f2: 0
if strcmp(class(A),class(B));
if isstruct(A)
Afields = sort(fieldnames(A));
Bfields = sort(fieldnames(B));
if alltrue(compare(Afields,Bfields))
for i=1:size(Afields,1)
field = Afields{i};
eval(['C.',field,'=compare(A.',field,',B.',field,');']);
end
else
error('Structs must have the same fields.');
end
elseif iscell(A)
if size(A)==size(B)
C = cellfun(@(a,b) compare(a,b),A,B,'UniformOutput',false);
else
error('Cell arrays must have the same size.');
end
elseif isnumeric(A) || islogical(A)
if size(A)==size(B)
C = A==B;
else
error('Numeric and logical arrays must have the same size.');
end
elseif ischar(A)
C = strcmp(A,B);
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