TravellingSalesWoman
TravellingSalesWoman

Reputation: 133

Converting a cell to matrix

I have an array of cells I want it to be converted into matrix of 2D

I did the following:

B = [9 8 8 8 10 10 10 10 9 9];
A = [8,9,10]; 
Y = arrayfun(@(x) find(B==x),unique(A),'Un',0);

The result is:

Y = {[2,3,4] , [1,10,9] , [5,6,7,8] } 

Now I want Y to be like this:

 Y = 2  3  4  0  0 0 0 0 0 0 
     1  10 9  0  0 0 0 0 0 0 
     5  6  7  8  0 0 0 0 0 0 

a 2D matrix with rows of size A and columns of size B , How can I do that in MATLAB?

Upvotes: 1

Views: 77

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

This may be faster, as it avoids cellfun:

Y = bsxfun(@eq, unique(A).', B); %'// compare elements from A and B
Y = bsxfun(@times, Y, 1:size(Y,2)); %// transform each 1 into its row index
[~, ind] = sort(~Y, 2); %// this will move zeros to the right
ind = bsxfun(@plus, (ind-1)*size(Y,1), (1:size(Y,1)).'); %'// make linear index
Y = Y(ind);

Upvotes: 0

Robert Seifert
Robert Seifert

Reputation: 25232

Just change your last line to:

Y = cell2mat(arrayfun(@(x) [find(B==x) 0*find(B~=x)],unique(A),'Uni',0).')

to also include all values which do not pass the condition and set them to zero. Then all cells have the same size and you can use cell2mat.

Y =

     2     3     4     0     0     0     0     0     0     0
     1     9    10     0     0     0     0     0     0     0
     5     6     7     8     0     0     0     0     0     0

Upvotes: 4

Related Questions