如何通过将数组转换为单个数字来保持前导零

问题描述:

所以我的问题是,当我尝试合并不同列中的数字时,前导零消失了,这是我的代码:

So my problem was, when i'm trying to combine number from different columns, leading zeros disappear, here's my code:

Bthree= [0  0   1
9   1   2
0   5   7]


len=size(Bthree);
    A=[];
    for jj=1:len(1)
        s=int2str(Bthree(jj,1:3));
        s=s(s~=' ');
        A(jj,:)=[str2num(s)];
    end

输出

1
912
57

如您所见,前导零消失了,但我希望保留零.

as you can see leading zeros disappear but i want zero to be keep

所需的输出:

001
912
057

那么我能做到吗?谢谢

如果要保留前导零,则可能需要将数据存储为字符串:

If you want to keep leading zeros you likely need to store your data as strings:

Bcell = strrep(cellstr(num2str(Bthree)),' ','')

返回我们的数字字符串的单元格数组.对于其他char数组,请执行以下操作:

returns a cell array of strings our your numbers. For a char array additional do:

Bchar = cell2mat(Bcell)

或者,您也可以直接通过以下方式获取char数组:

Or alternatively you can get the char array directly by:

Bchar = reshape(sprintf('%i',Bthree),size(Bthree))

返回:

Bcell = 

    '001'
    '912'
    '057'


Bchar =

001
912
057


由于您似乎不确定是否真的需要前导零,因此这里是转换为双精度的简短方法:


As you seem to be not sure if you really need the leading zeros, here a short way for the conversion to doubles:

Bdouble = str2num(Bchar)

Bdouble =

     1
   912
    57