how to delete empty elements in the cell in a way

2019-07-10 02:02发布

问题:

in MATLAB I have a cell array like this

a = { 1 2 2 3 4 5 [] []
      2 4 5 4 3 2 4 5 
      4 5 4 3 4 [] [] []}

I want to remove empty elements in a way that I get this :

a = { 1 2 2 3 4 5 2 4 5 4 3 2 4 5 4 5 4 3 4}

but when I use this : a(cellfun(@isempty,a)) = []; what I get is this :

a = {1 2 4 2 4 5 2 5 4 3 4 3 4 3 4 5 2 4 5}

which is not what I want

回答1:

The problem is that the linear index runs in the direction of rows, i.e. it runs through the first conlumn, then through the second column etc.

You can see this when you call reshape on a vector:

>> reshape([1 2 3 4 5 6 7 8 9],3,3)
ans =
     1     4     7
     2     5     8
     3     6     9

To achieve the result you want, you need to transpose a before indexing into it.

a = a';
a(cellfun(@isempty,a)) = [];


回答2:

You can try this : A(~cellfun('isempty',A))



标签: matlab row cell