How do you add a 0 in front of single digit numbers in a numerical array?

I later want to convert 2 numerical arrays into a string array and then back to a numerical array to combine a series of numbers. HOWEVER - to do this the numbers need to have the same amount of integers otherwise I get an empty matrix.
So my question is, how would I tell matlab to put a 0 in front a singular numbers in a 1x56 numerical array so all the numbers have the same amount of digits?

6 commentaires

Please show a small example of input(s) and desired output(s).
"put a 0 in front a singular numbers in a 1x56 numerical array so all the numbers have the same amount of digits" That's not possible with a numerical array.
The string array changes each time I run a scrip and will contain different numbers. at the moment the string variable has 14.1, 13.22, 12.1, 1.3. I would want it to out put into a numerical variable 14.01, 13.22, 01.03
"I would want it to out put into a numerical variable 14.01, 13.22, 01.03" As I said that is not possible.
However, "I would want it to out put into a character/string variable '14.01, 13.22, 01.03'" would have been possible.
Could I make another string variable that put a 0 in front of the single digits and then put that into a numerical array?
There is no such thing as leading zeros when it comes to numerical variables. Leading zeros in the string variable will vanish when "put that into a numerical".
Try to formulate your question/problem in other words.

Connectez-vous pour commenter.

Réponses (1)

num2str, fprintf and sprintf all have options to specify a format when converting a numeric value to a string.
a=num2cell(1:10);
b=cellfun(@(x) sprintf('%02d',x),a,'UniformOutput',false);

2 commentaires

Or the undocumented:
b = sprintfc('%02d', a);
Cool, that's even 20 times faster. Not strange, as you remove a lot of overhead.

Connectez-vous pour commenter.

Catégories

Tags

Aucun tag saisi pour le moment.

Commenté :

Rik
le 11 Oct 2017

Community Treasure Hunt

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

Start Hunting!

Translated by