行索引的笛卡尔积在Matlab中 [英] Cartesian product of row-indices in Matlab

查看:103
本文介绍了行索引的笛卡尔积在Matlab中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab中有一个尺寸为mxn且为m>n的二进制矩阵A.我想构造一个尺寸为cxn的矩阵B,逐行列出A中所包含的行索引的笛卡尔乘积的每个元素.为了更加清楚,请考虑以下示例.

I have a binary matrix A of dimension mxn with m>n in Matlab. I want to construct a matrix B of dimension cxn listing row wise each element of the Cartesian product of the row indices of the ones contained in A. To be more clear consider the following example.

示例:

  %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];

推荐答案

对于您的示例,可以使用combvec命令获得笛卡尔积:

You can get the cartesian product with the combvec command, for your example:

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


您可以使用产品的关联属性将此列扩展为未知的列数.


You can expand this to an unknown number of columns by using the associative property of the product.

[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.';

这篇关于行索引的笛卡尔积在Matlab中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆