how to delete empty elements in the cell in a way i want

喜欢而已 提交于 2019-12-11 01:43:37

问题


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))



来源:https://stackoverflow.com/questions/11505101/how-to-delete-empty-elements-in-the-cell-in-a-way-i-want

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!