在Matlab中marix行值的笛卡尔积

时间:2018-01-25 13:51:23

标签: matlab nan cartesian-product

this question类似,我在Matlab中有一个具有实数值的矩阵(包括维度NaN的{​​{1}} s)A。我想构建一个矩阵mxn,列出B列中A列中包含的值的非唯一笛卡尔积的每个元素。NaN。更清楚地考虑以下示例。

示例:

  %m=3;
  %n=3;

  A=[2.1 0 NaN;
     69 NaN 1;
     NaN 32.1 NaN];

  %Hence, the Cartesian product {2.1,0}x{69,1}x{32.1} is 
  %{(2.1,69,32.1),(2.1,1,32.1),(0,69,32.1),(0,1,32.1)} 

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


 B=[2.1 69 32.1;
    2.1 1 32.1;
    0 69 32.1;
    0 1 32.1];

1 个答案:

答案 0 :(得分:1)

我想出了一个使用细胞的解决方案:

function B = q48444528(A)
if nargin < 1
A = [2.1   0   NaN;
      69  NaN   1 ;
     NaN  32.1 NaN];
end
% Converting to a cell array of rows:
C = num2cell(A,2);
% Getting rid of NaN values:
C = cellfun(@(x)x(~isnan(x)),C,'UniformOutput',false);
% Finding combinations:
B = combvec(C{:}).';

输出:

B =

    2.1000   69.0000   32.1000
         0   69.0000   32.1000
    2.1000    1.0000   32.1000
         0    1.0000   32.1000