如何通过将数组转换为单个数字来保持前导零 [英] How to keep leading zeros by transforming array to single numbers

查看:88
本文介绍了如何通过将数组转换为单个数字来保持前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何通过将数组转换为单个数字来保持前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆