Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove empty cells in MATLAB

Tags:

matlab

cells

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?

like image 363
Matthias Pospiech Avatar asked Mar 14 '12 08:03

Matthias Pospiech


People also ask

How do you delete cells in MATLAB?

Delete the contents of a particular cell by assigning an empty array to the cell, using curly braces for content indexing, {} . Delete sets of cells using standard array indexing with smooth parentheses, () . For example, remove the second row of C .

How do you delete blank columns in MATLAB?

The easiest way to remove a row or column from a matrix is to set that row or column equal to a pair of empty square brackets [] .

How do you check if a cell is empty in MATLAB?

Description. TF = isempty( A ) returns logical 1 ( true ) if A is empty, and logical 0 ( false ) otherwise. An empty array, table, or timetable has at least one dimension with length 0, such as 0-by-0 or 0-by-5.


2 Answers

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

like image 69
Jonas Avatar answered Oct 16 '22 23:10

Jonas


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?

like image 43
Max Avatar answered Oct 17 '22 01:10

Max