A compact way to find single digit numbers (i.e. numbers between 0 and 9) and replace them with two digit numbers

8 visualizaciones (últimos 30 días)
A compact way to find single digit numbers (i.e. numbers between 0 and 9) and replace them with two digit numbers ?
For example, from:
a = [ 8
12
15
76
3
99
0];
I would like to add a zero in front of the single digit numbers:
b = [08
12
15
76
03
99
00];
  9 comentarios
dpb
dpb el 10 de Ag. de 2022
No problem from me...I was just thinking you were suggesting to put the 8-bits of zeros out based on the number of bits, not on the magnitude of the contained value it could hold.
But, agreed, it's taken off on a complete tangent...
Sim
Sim el 11 de Ag. de 2022
I did not think to cause such a fuss :-) ....but the conversation is very interesting, thanks!

Iniciar sesión para comentar.

Respuesta aceptada

John D'Errico
John D'Errico el 9 de Ag. de 2022
Editada: John D'Errico el 9 de Ag. de 2022
In MATLAB, you CANNOT store a number in a numeric format as one that has a leading zero.
If you want to convert the numbers to character form, then it is trivial. One line is sufficient.
a = [ 8
12
15
76
3
99
0];
d = dec2base(a,10)
d = 7×2 char array
'08' '12' '15' '76' '03' '99' '00'
The result is no longer usable as a number though. It is effectively only a picture of a number at that point, or perhaps I should say a caricature, if you can stand the pun.

Más respuestas (1)

dpb
dpb el 9 de Ag. de 2022
For what purpose and in what context? You will only be able to show the leading zeros if you convert the numeric values to some form of text in which case it's trivial
>> compose('%02d',a)
ans =
7×1 cell array
{'08'}
{'12'}
{'15'}
{'76'}
{'03'}
{'99'}
{'00'}
>>
Well, there is one other way --
>> categorical(ans)
ans =
7×1 categorical array
08
12
15
76
03
99
00
>>
but if you want a straight, ordinary double array to appear that way at the command line, just not possible.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by