更通用的方法:
%// find and count unique elements
[a,b] = hist(target,unique(target));
%// Create vectors according to target and number occurences and store them in cell array
temp = arrayfun(@(x,y) y*ones(x,1),a,b,'uni',0)
另一种可能更快的方法是:
%// get indices of unique values
[~,~,c] = unique(target)
%// Create vectors according to indices and store them in cell array
temp = accumarray(c(:),target(:),[],@(x) {x})
我个人建议您在此停止并继续使用元胞数组!
如果您知道有多少独特元素并且您真的想将它们存储在单独的变量中,您可以使用:
[A,B,C] = temp{:}
我能想到的最通用和最容易出错的方法是:
%// create a map container with all values you're expecting and it's corresponding specifier
valueSet = {'A', 'B', 'C'};
keySet = [100 200 400];
mapObj = containers.Map(keySet,valueSet)
%// create a struct and distribute keys to specifier
for ii = 1:numel(keySet);
out.(mapObj(keySet(ii))) = target(target == keySet(ii));
end
你会得到一个结构体out,其中包含A、B 和C 字段:
有趣的是,您还可以自动生成keySet 和valueSet:
%// keySet are all unique values of target
keySet = unique(target)
%// create specifiers according to number of unique elements
valueSet = cellstr(char(65:65+numel(keySet)-1).') %'
%// you get 'A' 'B' and 'C' to use as field names
这样您就不需要知道哪些是您的元素以及您实际拥有多少不同的元素。与原始请求的唯一区别是您没有获得变量 A、B 和 C,而是获得了 out.A、out.B 和 out.C