我已经写了一个脚本,循环通过几个matrices。我得到的输出如下所示:
10,40,50
20,60,50,80
30,50,70,110
30,70,110以此类推。
我想要做的是计算有多少独特的配置文件存在,如果一个矩阵包含10,40,50,它将被计数为一个标记为( 10,40,50 )的配置文件,如果它将找到另一个完全相同的矩阵(10,40,50),它应该打印:10,40,50找到2次迭代。
总而言之,我有一个遍历矩阵的脚本。它们包含不同的值,它们不时地重复自己,我想计算所有存在的唯一配置文件。假设我们输入以下内容:
10,40,50
10,40,50
10,40,50
30,50,70,110
20,60,50,80
30,50,70,110
10,40,50
10,40,50输出应该是(但是可以输出计数):
10,40,50 found 5 time
20,60,50,80 found 1 time
30,50,70,110 found 2 time非常非常感谢你的帮助,为一个爱好项目做这件事。
编辑:这不是我使用的单元格数组,而是我正在循环的<1x500>向量。
发布于 2016-07-18 07:13:24
(遗憾的是,unique函数不能在数值向量的单元数组上工作。)
您可以按如下方式进行操作:
x = { [10,40,50];
[10,40,50]
[10,40,50];
[30,50,70,110];
[20,60,50,80];
[30,50,70,110];
[10,40,50];
[10,40,50] };
[ii, jj] = ndgrid(1:numel(x)); % indices of all pairs
m = cellfun(@isequal, x(ii), x(jj)); % all pairwise comparisons
[u, v] = unique(m, 'rows', 'stable'); % unique rows, and their indices
count = sum(u,2); % result: number of repetitions
unique_x = x(v); % result: unique vectors这给了我们
>> celldisp(unique_x)
unique_x{1} =
10 40 50
unique_x{2} =
30 50 70 110
unique_x{3} =
20 60 50 80
>> count
count =
5
2
1要以所需格式显示,请执行以下操作:
for n = 1:numel(unique_x)
disp([mat2str(unique_x{n}) ' found ' num2str(count(n)) ' time(s)'])
end打印
[10 40 50] found 5 time(s)
[30 50 70 110] found 2 time(s)
[20 60 50 80] found 1 time(s)如果结果是在循环中获得的:将它们收集到一个单元数组中,然后应用上面的内容:
x = cell(1,num_iter); % preallocate if possible
for iter_index = 1:num_iter
% Do stuff that gives a vector iter_result as a result
x{iter_index} = iter_result;
end
% Now apply above code to x发布于 2016-07-18 07:24:35
我猜您的脚本输出是一个单元格数组,因为我的即席回答就是基于这个假设。因此,如果脚本的输出是:
output = {[10,40,50];
[10,40,50];
[10,40,50];
[30,50,70,110];
[20,60,50,80];
[30,50,70,110];
[10,40,50];
[10,40,50]};我们可以将您的输出转换为字符串格式。差劲,但有效:):
tmp = cellfun(@num2str,output,'UniformOutput',false);然后我们使用unique函数:
[a,b,c]=unique(tmp);其中a是tmp的唯一字符串,b是该字符串在tmp中的第一次出现,c显示tmp中的哪个元素对应于a中的哪个元素,即将tmp映射到a。我们现在要做的就是计算向量c中有多少1-s,2-s,3-s等。为此,我更喜欢使用一个简单的循环:
for k = 1:length(b)
n(k) = nnz(c == k);
disp(['[',a{k},'] found ',num2str(n(k)),' time(s)'])
end因此,最终输出是:
[10 40 50] found 5 time(s)
[20 60 50 80] found 1 time(s)
[30 50 70 110] found 2 time(s)希望这能有所帮助
发布于 2016-07-18 15:52:24
output = {[10,40,50];
[10,40,50];
[10,40,50];
[30,50,70,110];
[20,60,50,80];
[30,50,70,110];
[10,40,50];
[10,40,50]};
tmp = cellfun(@num2str,output,'UniformOutput',false); % number to string
[a,~,c] = unique(tmp); % find unique profiles and index from tmp to a
count = accumarray(c,1); % count same index in c然后
for k = 1 : length(a)
fprintf('[ %s ] found %d time(s)\n',a{k},count(k));
end显示与其他答案相同的消息。
https://stackoverflow.com/questions/38426576
复制相似问题