【问题标题】:Find the number of occurence of a matrix in cell查找单元格中矩阵的出现次数
【发布时间】:2017-04-10 09:16:25
【问题描述】:

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

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}

没有循环也能找到吗?

提前致谢!

【问题讨论】:

  • “出现次数”是什么意思?可能的重叠怎么办?此外,如果B 是矩阵而不是元胞数组,它会更容易(更快)
  • 这正是问题所在,我实际上想将该矩阵视为一种模式。

标签: matlab matrix cell


【解决方案1】:

使用 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));

【讨论】:

  • 谢谢!不知何故,使用 for 循环似乎更快。
  • 确实如此。第二个版本要多次进出细胞,使整个过程更长。
【解决方案2】:

您可以“滥用”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)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-28
    • 2021-06-12
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多