Search code examples
matlabmatrixcell-arrayzero

How to remove zero values from a cell array in Matlab


I have a cell array in MATLAB which looks like this,

arr=  4  5  8
     22 23  0

Zero values always appear at the end of the last row. If there are two zero values it will look like this,

arr=  4  5  8
     22  0  0

There is no row contains zeros for its all positions. Could anyone help me to remove those zero values exists in the last row? What I want is something like this

arr=  4   5   8
     22  23

Solution

  • If you have scalars at every index of the cell array then convert arr to a matrix, find the indices where zeros are present and then replace them with [].

    arr([arr{:}]==0)={[]};