-
Notifications
You must be signed in to change notification settings - Fork 36
/
maxdiff.m
77 lines (74 loc) · 1.36 KB
/
maxdiff.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
function e = maxdiff(a,b,rel)
% MAXDIFF(A,B) returns the maximum difference in any field or element.
% Matching infinities or NaNs do not count.
%
% MAXDIFF(A,B,REL) measures the per-element relative difference (A-B)/(REL + A)
%
% Examples:
% maxdiff([1 2 3 nan inf -inf],[1 2 4 nan inf -inf]) % = 1
% Written by Tom Minka
% (c) Microsoft Corporation. All rights reserved.
if nargin < 3
rel = [];
end
e = 0;
if ~isequal(class(a), class(b))
fprintf('maxdiff: incompatible types\n');
e = Inf;
return
end
if isa(a,'struct')
for f = fieldnames(a)'
field = char(f);
if ~isfield(b,field)
fprintf('maxdiff: second argument lacks field %s\n', field);
e = Inf;
return
end
e = max(e,maxdiff(a.(field), b.(field), rel));
end
return
end
if ~isequal(size(a),size(b))
fprintf('maxdiff: size mismatch\n');
e = Inf;
return
end
a = a(:);
b = b(:);
if iscell(a)
for i = 1:numel(a)
e = max(e,maxdiff(a{i},b{i}));
end
return
end
i = isnan(a);
if any(i ~= isnan(b))
% mismatched NaNs
e = Inf;
return
elseif sum(i) > 0
a = a(~i);
b = b(~i);
end
i = ~isfinite(a);
if any(i ~= ~isfinite(b))
% mismatched infs
e = Inf;
return
elseif ~isequal(a(i),b(i))
e = Inf;
return
else
a = a(~i);
b = b(~i);
end
if isempty(a)
e = 0;
return
end
e = abs(a(:) - b(:));
if ~isempty(rel)
e = e ./ (rel + abs(a(:)));
end
e = max(e);