remove empty cells in MATLAB

回眸只為那壹抹淺笑 提交于 2019-12-30 03:22:09

问题


I want to remove all empty cells at the bottom of a matlab cell array. However all code example that I found collapse the matrix to a vector, which is not what I want.

So this code

a = { 1, 2; 3, 4; [], []}
emptyCells = cellfun('isempty', a); 
a(emptyCells) = []

results in this vector

a = [1] [3] [2] [4]

But I want instead this array

a =

[1]    [2]

[3]    [4]

How would I do that?


回答1:


If you want to delete all the rows in your cell array where all cell are empty, you can use the follwing:

a = { 1, 2; 3, 4; [], []}
emptyCells = cellfun('isempty', a); 

a(all(emptyCells,2),:) = []

a = 
    [1]    [2]
    [3]    [4]

The reason it didn't work in your formulation is that if you index with an array, the output is reshaped to a vector (since there is no guarantee that entire rows or columns will be removed, and not simply individual elements somewhere).




回答2:


This works for me:

a = { 1, 2; 3, 4; [], []};
emptyCells = cellfun('isempty', a);
cols = size(a,2);
a(emptyCells) = [];
a = reshape(a, [], cols);

but I'm not sure if it will be general enough for you - will you always have complete rows of empty cells at the bottom of your array?




回答3:


There is a function that generalizes the removing specific row/columns from a cell, which is called fun_removecellrowcols. Due to the removal, cell dimensions are resized.




回答4:


A simpler solution very specific to your problem is to convert the cell directly into a matrix:

cleanedA = cell2mat(a);

It converts to a normal matrix, and while doing this it removes the empty cells.

Then, of course, you can reconvert it to a cell array with the following command:

a = mat2cell(cleanedA, [1 1], [1 1])

Its not generic, but for the example posted it is the simplest solution I can think of.



来源:https://stackoverflow.com/questions/9697900/remove-empty-cells-in-matlab

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