Reputation: 27
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.
Upvotes: 0
Views: 656
Reputation: 4652
You might consider preallocating memory, i.e., creating an empty C
cell array before you start to fill it:
X = [1,4,6,9; 2,3,6,7; 5,9,8,7; 9,8,7,10];
Mrows = numel(X(:,1));
C = cell(Mrows,1); %preallocate memory
for i = 1:Mrows
C{i} = X(i,X(i,:)<=6,:);
end
Upvotes: 0
Reputation: 4195
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];
[]
}
Upvotes: 0