MATLAB: How to delete the rest of the zeros from a matrix

cluster

suppose this the output c=[0 0 0 0; 0 0 0 0; 1 1 1 1] now how could i delete the other zeros for a looop and only print the last row??

Best Answer

  • To remove 0, you can simply do: c(~c) = []; you don't need a loop! Beauty of matlab :)
    ~c is essentially looking for empty values in c. In Matlab, 0 means empty value and you can simply remove it by replacing it with []
    >> c=[0 0 0 0; 0 0 0 0; 1 1 1 1]
    c =
    0 0 0 0
    0 0 0 0
    1 1 1 1
    >> c(~c) = []
    c =
    1 1 1 1
    >>