1

Similarly to this question, I have a matrix with real values (including NaNs) A of dimension mxn in Matlab. I want to construct a matrix B listing row-wise each element of the non-unique Cartesian product of the values contained in As columns which are not NaN. To be more clear consider the following example.

Example:

  %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];
Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
Codevan
  • 538
  • 3
  • 20

1 Answers1

1

I came up with a solution using cells:

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{:}).';

Output:

B =

    2.1000   69.0000   32.1000
         0   69.0000   32.1000
    2.1000    1.0000   32.1000
         0    1.0000   32.1000
Dev-iL
  • 23,742
  • 7
  • 57
  • 99