找出单元格中矩阵的出现次数

时间:2017-04-10 09:16:26

标签: matlab matrix cell

我们假设我们有一个这样的矩阵:

A = [1 2 3 4]

如何在这样的单元格中找到此矩阵的出现次数:

B{1,1} = {1, 7, 5, 7, 1, 2 ,3 ,4 ,9 ,4 ,6 ,1 ,2 ,3 ,7}
B{1,2} = {2, 3, 4, 5, 6, 0, 5, 1, 2, 3, 4, 5, 2, 1, 0}

是否可以在没有循环的情况下找到它?

提前致谢!

2 个答案:

答案 0 :(得分:2)

for循环解决方案: 没有for循环也是可能的,但它是一个可读性的噩梦。我不建议。

  numElA = numel(A);
    out    = zeros(size(B));
    for j = 1 : numel(B) % for every cell of B
        b = B{j}; % extract matrix
        for i = 1 : numel(b)-numElA % for every element of b (minus the size of A)
            out(j) = out(j) + all(cat(2,b{i+[0:numElA-1]})==A); % compare the two vectors (indexed b and a). If they are the same count them +1
        end
    end

更新:这是没有for循环的版本

indA = 1:numel(A);
indB = cellfun(@(x) num2cell(bsxfun(@plus,(1:numel(x)-max(indA))',indA-1),2),B,'uniformoutput',false);
out  = cellfun(@sum,cellfun(@(MAT,IND) cellfun(@(ind) all(cat(2,MAT{ind})==A),IND),B,indB,'UniformOutput', false));

答案 1 :(得分:1)

你可以"滥用" strfind,假设您可以将B1和B2存储为矩阵而不是单元格。您仍然可以使用单元格作为外层,以支持不同长度的输入。

% Convert storage format
C{1} = cell2mat(B{1,1});
C{2} = cell2mat(B{1,2});

indices = cellfun(@(c) strfind(c,A), C, 'UniformOutput', false);

这将查找每个数组中的所有起始索引。如果您只想要总数,请计算出现次数:

occurrences = cellfun(@(c) length(strfind(c,A)));