elementcount.m
来自「一个关于数据聚类和模式识别的程序,在生物化学,化学中因该都可以用到.希望对大家有」· M 代码 · 共 64 行
M
64 行
function [sortedElement, count] = elementCount(in)
%elementCount: Count elements in a vector.
% Usage: [sortedElement, count] = elementCount(in)
%
% For example:
% in = [5 1 5 5 7 9 9];
% fprintf('in = %s\n', mat2str(in));
% fprintf('"[sortedElement, count] = elementCount(in)" produces the following output:\n');
% [sortedElement, count] = elementCount(in);
% fprintf('sortedElement = %s\n', mat2str(sortedElement));
% fprintf('count = %s\n\n', mat2str(count));
% in = {'ab', 'cd', 'ef', 'ab', 'cd', 'ab'};
% fprintf('in = %s\n', '{''ab'', ''cd'', ''ef'', ''ab'', ''cd'', ''ab''}');
% fprintf('"[sortedElement, count] = elementCount(in)" produces the following output:\n');
% [sortedElement, count] = elementCount(in);
% fprintf('sortedElement = %s\n', '{''ab'', ''cd'', ''ef''}');
% fprintf('count = %s\n', '[3 2 1]');
%
% Type "elementCount" for a self demo.
% Roger Jang, 19970327, 20071009
if nargin<1, selfdemo; return, end
if isnumeric(in) % Numerical vector
[m,n] = size(in);
in1 = sort(in);
in1(end+1)=in1(end)+1;
index = find(diff(in1) ~= 0);
sortedElement = in1(index);
if n==1
count = diff([0; index]);
else
count = diff([0, index]);
end
end
if iscell(in) % Cell string
[m,n] = size(in);
in1 = sort(in);
in1{end+1}=[in1{end}, 'z'];
index = find(strcmp(in1(1:end-1), in1(2:end))==0);
sortedElement = in1(index);
if n==1
count = diff([0; index]);
else
count = diff([0, index]);
end
end
% ====== Seld demo ======
function selfdemo
in = [5 1 5 5 7 9 9];
fprintf('in = %s\n', mat2str(in));
fprintf('"[sortedElement, count] = elementCount(in)" produces the following output:\n');
[sortedElement, count] = elementCount(in);
fprintf('sortedElement = %s\n', mat2str(sortedElement));
fprintf('count = %s\n\n', mat2str(count));
in = {'ab', 'cd', 'ef', 'ab', 'cd', 'ab'};
fprintf('in = %s\n', '{''ab'', ''cd'', ''ef'', ''ab'', ''cd'', ''ab''}');
fprintf('"[sortedElement, count] = elementCount(in)" produces the following output:\n');
[sortedElement, count] = elementCount(in);
fprintf('sortedElement = %s\n', '{''ab'', ''cd'', ''ef''}');
fprintf('count = %s\n', '[3 2 1]');
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?