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?
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 .
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 [] .
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.
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).
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With