Search code examples
arrayssortingmatlabvectordigit

Separating numbers (in a single line array) with more than 2 digits into several columns


Is there a way to separate

`vector=[0345;0230;0540;2340]`

into

`vec_1=[03;02;05;23]`

and

`vec_2=[45;30;40;40]`

Solution

  • My solution:

    v = [0345;0230;0540;2340];
    vv = num2str(v,'%04d');    %# convert to strings, 4 digits, fill with zeros
    v1 = str2num( vv(:,1:2) )  %# extract first two digits, convert back to number
    v2 = str2num( vv(:,3:4) )  %# extract last two digits, convert back to number
    

    The result:

    v1 =
         3
         2
         5
        23
    v2 =
        45
        30
        40
        40
    

    Of course, if you want the result as a cell-array of strings (with any leading zeros kept), use:

    >> v1 = cellstr(num2str(v1,'%02d'))
    v1 = 
        '03'
        '02'
        '05'
        '23'