Search code examples
arraysmatlabvectortrim

Delete leading zeros from vector in Matlab


Can I trim the leading zeros in vectors [0 0 0 2 8 12] , [0 1 8 0 3 0] , [0 0 0 0 25 0] off so to get [2 8 12] , [1 8 0 3 0] , [25 0] with the same function? Is there a way to do it without using a while loop? (Or any other kind of loop?)

I intend to turn the vector into a string, such as '2h 8m 12s', '1mo 8d 0h 3m 0s', '25m 0s', if that will open any doors.


Solution

  • As mentionend by @Luis Mendo find() will do the trick.

    a=[0 0 0 2 8 12];
    b=[0 1 8 0 3 0];
    c=[0 0 0 0 25 0];
    
    a_short = a(find(a>0,1):end);
    b_short = b(find(b>0,1):end);
    c_short = b(find(c>0,1):end);
    

    The ">0" part in find() is not necessary, but i feel like it helps in regards to readability