Search code examples
matlab3dcell-array

Deleting empty rows in a 3D cell array in Matlab


I have a large 3D CELL ARRAY (x1) which I have to delete the empty rows. How can I do this?

Example of my cell array (some pieces of the variable):

val(:,:,1) = 

[20]    []    []    []    []    []    []    []
[ 0]    []    []    []    []    []    []    []
[ 0]    []    []    []    []    []    []    []
[]      []    []    []    []    []    []    []

(...)

val(:,:,42) = 


[ 34225]    [   215]    [    0]    [   0]    [    0]    [    0]    [    0]    [    0]
[ 85200]    [   545]    [    0]    [   0]    [    0]    [    0]    [    0]    [    0]
[ 65074]    [   190]    [ 1000]    [   0]    [    0]    [    0]    [    0]    [    0]
[ 81570]    [  1385]    [ 2475]    [   0]    [    0]    [    0]    [    0]    [    0]    
[ 67236]    [   530]    [  365]    [   0]    [    0]    [    0]    [    0]    [    0]
[ 61338]    [     0]    [  100]    [   0]    [    0]    [    0]    [    0]    [    0]
[]          []          []         []        []         []         []         []    
[]          []          []         []        []         []         []         []  
[]          []          []         []        []         []         []         []   

In this case, I want to exclude the 4th row of (:,:,1), the three last rows from (:,:,42) and all the others from these variable.

I've tried

x1(all(all(cellfun((@isempty,x1),2),:,:) = [];

But it gave me this following error:

Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.

PS: I cannot use "==" because its a cell array.

Thanks in advance


Solution

  • There seem to be two problems here. One is the fact that you are using a 3D cell array, and it appears that you want to delete different numbers of rows from different planes. This would give you something that does not form a proper MxNxP structure, because M won't be the same.

    That said, I can tell you how to remove the rows that are all empty in a 2D cell array. Let's say val is MxN. Then

    val2 = val(~all(cellfun(@numel,val)==0,2),:);
    

    If you want to work with the 3D data you described, you'll have to store the result for each plane separately in a cell. Something like this:

    val2 = cell(1,1,size(val,3));
    for i = 1:size(val,3)
        valplane = val(:,:,i);
        val2{i} = valplane(~all(cellfun(@numel,valplane)==0,2),:);
    end