Search code examples
arraysmatlabmatrixcellcell-array

MATLAB - Using mat2cell to divide a MxN matrix into 1xM cell with different sizes within


This is the problem:

I have a matrix with MxN size and I want divide it into a cell of size 1xM, but each row M of the cell contains an array of size 1xNi (this means the arrays have different size).

I am trying to do this using mat2cell function but I want to avoid using loops and I don't know how to do it.

I will try to explain my problem with an example. Suppose that I have a matrix

X = [1,4,6,9; 2,3,6,7; 5,9,8,7; 9,8,7,10]

What I want the code to do is take the values X<=6 of each row and put them in a 1xM cell. So the answer should be:

ans =


C{1} = [1,4,6]
C{2} = [2,3,6]
C{3} = [5]
C{4} = []

So far I have created a loop which goes through all rows of the matrix to find the elements that meet the condition:

for i = 1:Mrows
    C{i} = X(i,X(i,:)<=6,:);
end

This gives me the result I want but it takes too much time specially when the size of the matrix is very big.


Solution

  • you can use num2cell(A,2) to convert each row into a cell and then apply cellfun to remove values smaller than 6:

    X = [1,4,6,9; 2,3,6,7; 5,9,8,7; 9,8,7,10];
    C = num2cell(X,2);
    res = cellfun(@(x) x(x<=6),C,'UniformOutput',0);
    

    and you get:

    {
     [1,4,6];
     [2,3,6];
     [5];
     []
    }