【问题标题】:delete sub-matrices within a large matrix删除大矩阵中的子矩阵
【发布时间】:2015-03-26 10:31:22
【问题描述】:

我正在生成一个包含所有可能的零和一组合的大型矩阵,如下所示:

X = dec2base(0:power(2,M*K)-1,2) - '0'; 
combinations = reshape(permute(X,[3 2 1]),M,K,[]);

在combinations 内的每个矩阵中,我需要删除在其一列或多列中具有多个“1”的矩阵。 例如: 如果 combinations(:,:,j) 对于 j 的任何值是 combinations(:,:,j)=[1 0 0 0;1 0 0 1] 即它的第一列中有两个“1”值,我需要使用combinations(:,:,j)=[] 将其删除,所以,我的问题是如何测试我的情况?

【问题讨论】:

  • 一开始最好不要生成整个矩阵。你想生成什么?
  • @knedlsepp,我想生成一个矩阵,该矩阵包含在所有可能的二进制元素矩阵中,在任何列中不超过一个“1”

标签: matlab matrix


【解决方案1】:

换个说法:找到any 列sum 是>1 的矩阵并删除它们

在代码中:

logical_index=any(sum(combinations,1)>1,2)
combinations(:,:,logical_index)=[]

【讨论】:

    【解决方案2】:

    正如您所解释的,您希望生成一个包含所有可能的二进制元素矩阵的矩阵,该矩阵在任何列中都不超过一个“1”,准确地构建您的矩阵可能很多比生成一个更大的矩阵然后进行一些修剪操作更快。 (是的,即使涉及for-loops!)

    版本 1 - 循环 dim=3,矢量化 dim=[1,2]:

    %// Input
    M = 7;
    K = 3;
    %// Computation
    Vs = [zeros(M,1), eye(M)];
    [numGrid{1:K}] = ndgrid(1:M+1);
    Nums = reshape(cat(3, numGrid{:}), [], K);
    
    combinations = zeros(M, K, size(Nums,1));
    for i = 1:size(Nums,1)
        combinations(:,:,i) = Vs(:,Nums(i,:));
    end
    

    或者,如果您想要更快的方法:

    版本 2 - 循环 dim=[1,2],矢量化 dim=3:

    %// Input
    M = 7;
    K = 3;
    %// Computation
    Vs = [zeros(M,1), eye(M)];
    [numGrid{1:K}] = ndgrid(1:M+1);
    Nums = reshape(cat(3, numGrid{:}), [], K);
    
    combinations = zeros(M, K, size(Nums,1));
    for i = 1:M
        for j = 1:K
            combinations(i,j,:) = Vs(i,Nums(:,j));
        end
    end
    

    版本 3 - 使用 bsxfun 完全矢量化

    %// Input
    M = 7;
    K = 3;
    %// Computation
    [numGrid{1:K}] = ndgrid(0:M);
    Nums = reshape(cat(3, numGrid{:}), [], K);
    combinations = bsxfun(@eq, (1:M).', permute(Nums,[3,2,1]));
    

    对于M = 7 和K = 3,所有这些都至少比原始方法快1000 倍。

    【讨论】:

    • @AmiraAkra:现在应该可以了。这不会让M=8;K=3 的记忆死亡。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多