1

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

Output

1
912
57

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

desired output:

001
912
057

so can i do that? thanks

Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
Raldenors
  • 311
  • 1
  • 4
  • 15

2 Answers2

2

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

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

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

Bchar = cell2mat(Bcell)

Or alternatively you can get the char array directly by:

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

returning:

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
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
  • how about you have m x n array? is it still applicable? – Raldenors Feb 25 '15 at 10:48
  • @Raldernors in my understanding `Bthree` is already an m x n array (though m = n), it works for any m and n. – Robert Seifert Feb 25 '15 at 10:50
  • the output is char cell, how can you convert it into number cell where zero don't disappear? – Raldenors Feb 25 '15 at 11:02
  • @Raldenors it's not possible. What number exists with leading zeros? For what purpose? You should ask a new question with a little wider context, so we can help you with your problem. But apart from binary numbers, *normal* numbers can't be stored as numbers (numerical) with leading zeros. – Robert Seifert Feb 25 '15 at 11:05
  • basically i want it to be involve in mathematical operation and you can't add or minus char cell or string cell to number cell – Raldenors Feb 25 '15 at 11:07
  • 1
    @Raldenors, of course not, but **what do you need the leading zeros for then?** – Robert Seifert Feb 25 '15 at 11:08
0

Replace the int2str with num2str.

Then your code should look like:

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

A=[];
for jj=1:size(Bthree,1)
    s=num2str(Bthree(jj,1:3));
    A(jj,:)=[str2num(s)];
end
Xxxo
  • 1,784
  • 1
  • 15
  • 24