Maria
Maria

Reputation: 33

Put all 1s of matrix in column 1, 2s in column 2 etc. and NaNs in empty cells

I want to put all 1's in column 1, all 2's in column 2 etc. of a matrix A. All NaNs should just be placed in the remaining empty cells.

For example,

A =  [1 2 3; 1 2 NaN; 1 3 NaN; 2 3 NaN; 2 NaN NaN; 3 NaN NaN; NaN NaN NaN]
A =

     1     2     3
     1     2   NaN
     1     3   NaN
     2     3   NaN
     2   NaN   NaN
     3   NaN   NaN
   NaN   NaN   NaN

And I would like to get

 B =

     1     2     3
     1     2   NaN
     1   NaN     3
   NaN     2     3
   NaN     2   NaN
   NaN   NaN     3
   NaN   NaN   NaN

EDIT: in the general case I have more numbers {1,2,...,N} and then NaN and need to be able to do the exercise for an arbitrary number of distinct numbers.

Upvotes: 3

Views: 73

Answers (1)

merch
merch

Reputation: 945

This code should do what you are trying to achieve:

%% Initialise
A    = [1 2 3; 1 2 NaN; 1 3 NaN; 2 3 NaN; 2 NaN NaN; 3 NaN NaN; NaN NaN NaN];
minA = min(min(A));
maxA = max(max(A));


%% For-loop example
B = NaN(size(A, 1), maxA);

for i=1:size(B, 2)
    log_i       = sum(A==i, 2)==1;
    B(log_i, i) = i;
end


%% Vectorized form example
index   = minA:maxA; 
index3D = reshape(index, 1, 1, maxA);

% 3D logical
check = bsxfun(@eq, repmat(A, 1, 1, maxA), index3D);

% Set C
C         = bsxfun(@times, double(check), index3D);
C         = squeeze(sum(C, 2));
C(C<minA) = NaN; % apply NaNs

Upvotes: 3

Related Questions