Matlab中行索引的笛卡尔积

3

我有一个在Matlab中维度为mxn的二进制矩阵A,其中m>n。我想构建一个维度为cxn的矩阵B,按行列出包含在A中的1的行索引的笛卡尔积的每个元素。为了更清楚地说明,请考虑以下示例。

示例:

  %m=4;
  %n=3;

  A=[1 0 1;
     0 0 1;
     1 1 0;
     0 0 1];

  %column 1: "1" are at rows {1,3}
  %column 2: "1" are at row {3}
  %column 3: "1" are at rows {1,2,4}

  %Hence, the Cartesian product {1,3}x{3}x{1,2,4} is 
  %{(1,3,1),(1,3,2),(1,3,4),(3,3,1),(3,3,2),(3,3,4)} 

  %I construct B by disposing row-wise each 3-tuple in the Cartesian product

  %c=6

 B=[1 3 1;
    1 3 2;
    1 3 4;
    3 3 1;
    3 3 2;
    3 3 4];
4个回答

4
您可以使用 combvec 命令获得笛卡尔积,对于您的示例:
A=[1 0 1;...
   0 0 1;...
   1 1 0;...
   0 0 1];

[x y]=find(A);

B=combvec(x(y==1).',x(y==2).',x(y==3).').';

% B =
%    1   3   1
%    3   3   1
%    1   3   2
%    3   3   2
%    1   3   4
%    3   3   4

通过使用乘法的结合律,您可以将此扩展到未知数量的列。

[x y]=find(A);

u_y=unique(y);

B=x(y==u_y(1)).';

for i=2:length(u_y)
    B=combvec(B, x(y==u_y(i)).');
end

B=B.';

1
警告。combvec属于神经网络工具箱。 - rayryeng

3

一种没有工具箱的解决方案:

A=  [1 0 1;
     0 0 1;
     1 1 0;
     0 0 1];



[ii,jj] = find(A)

kk = unique(jj); 

for i = 1:length(kk)
    v{i} = ii(jj==kk(i));
end

t=cell(1,length(kk));
[t{:}]= ndgrid(v{:});

product = []
for i = 1:length(kk)
    product = [product,t{i}(:)];
end

有趣的是,我看到我们的代码很相似,除了索引和创建矩阵方面存在一些细微差异。 - edwinksl

3
你可以使用accumarray来获取每一列非零元素所在行的向量。这适用于任意列数
[ii, jj] = find(A);
vectors = accumarray(jj, ii, [], @(x){sort(x.')});

然后应用此答案来有效地计算这些向量的笛卡尔积:

n = numel(vectors);
B = cell(1,n);
[B{end:-1:1}] = ndgrid(vectors{end:-1:1});
B = cat(n+1, B{:});
B = reshape(B,[],n);

在你的例子中,这就是

B =
     1     3     1
     1     3     2
     1     3     4
     3     3     1
     3     3     2
     3     3     4

2
简而言之,我会使用find来生成笛卡尔积所需的索引,然后使用ndgrid来执行这些索引的笛卡尔积。代码如下:
```python ind = find(condition) X = np.ndgrid(*[ind]*n) ```
其中,`condition`是条件,`n`是维度数。
clear
close all
clc

A = [1 0 1;
     0 0 1;
     1 1 0;
     0 0 1];

[row,col] = find(A);
[~,ia,~] = unique(col);
n_cols = size(A,2);
indices = cell(n_cols,1);

for ii = 1:n_cols-1
  indices{ii} = row(ia(ii):ia(ii+1)-1);
end
indices{end} = row(ia(end):end);

cp_temp = cell(n_cols,1);
[cp_temp{:}] = ndgrid(indices{:});

cp = NaN(numel(cp_temp{1}),n_cols);
for ii = 1:n_cols
  cp(:,ii) = cp_temp{ii}(:);
end
cp = sortrows(cp);
cp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接