function [type majority singular] = uniformity(x)
%[type majority singular] = uniformity(x)
% checks uniformity of vector x and returns
% 1 when x is uniform (or all elements are the same),
% 2 when x is uniform except for a single element with a different value,
% or 3 when x is multiform (contains three or more values).
% In the cases of 1 and 2, the value of the majority is returned. In the case
% of 2, the value of the singular element is also returned.
% (ja.doukaku.org Q53)
majority = -1; singular = -1;
r = unique(x);
h = histc(x,r);
[hs k] = sort(h,'descend');
type = length(r);
if type==1
majority = r(k(1));
elseif type==2 && hs(2)==1
majority = r(k(1));
singular = r(k(2));
else
type = 3;
end
shg #2702() [ Matlab ] Rating0/0=0.00
本質の部分はuniqueで種類を取り出してhistcで数えてsortで数の多い順にするところまでだが、その後各場合によって条件分岐して出力を整えるところはあまりすっきりしてない。
function [type majority singular] = uniformity(x) %[type majority singular] = uniformity(x) % checks uniformity of vector x and returns % 1 when x is uniform (or all elements are the same), % 2 when x is uniform except for a single element with a different value, % or 3 when x is multiform (contains three or more values). % In the cases of 1 and 2, the value of the majority is returned. In the case % of 2, the value of the singular element is also returned. % (ja.doukaku.org Q53) majority = -1; singular = -1; r = unique(x); h = histc(x,r); [hs k] = sort(h,'descend'); type = length(r); if type==1 majority = r(k(1)); elseif type==2 && hs(2)==1 majority = r(k(1)); singular = r(k(2)); else type = 3; endRating0/0=0.00-0+
[ reply ]