How to pad all numbers in array ?

How can I pad a vector of number with zeros ? I am able to do it with a for loop but I was wondering if there is a neater way to do it ?
For example,
a = [1 2 3 4 5];
b = sprintf('%06d',a);
gives me '000001000002000003000004000005'
I would like it to be [000001 000002 .....];

1 comentario

Stephen23
Stephen23 el 11 de Dic. de 2016
Editada: Stephen23 el 11 de Dic. de 2016
Floating point numeric values do not store explicit leading zeros. Even if you typed them, the zeros have no mathematical significance:
>> [000001,000002]==[1,2]
ans =
1 1

Iniciar sesión para comentar.

 Respuesta aceptada

Stephen23
Stephen23 el 11 de Dic. de 2016
b = sprintf(' %06d',a{:});
^ add this space

3 comentarios

RuiQi
RuiQi el 11 de Dic. de 2016
Editada: RuiQi el 11 de Dic. de 2016
its not giving me a cell of 1 row and 5 column it gives me c =
000001 000002 000003 000004 000005.
Id like it to be b = 1 x 5 cell = [000001, 000002, 00003....] I thought its something like the comma separated lists but
b = [sprintf('%06d',a{:})]; also does not work
Stephen23
Stephen23 el 11 de Dic. de 2016
Editada: Stephen23 el 11 de Dic. de 2016
There is no simple way to create a cell array of strings, but this works:
c = cellfun(@(n)sprintf('%06d',n),a,'UniformOutput',false)
Or you can read about the undocumented function sprintfc:
RuiQi
RuiQi el 11 de Dic. de 2016
wow sprintfc works very nicely. and i will also read through the cellfun

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 11 de Dic. de 2016

1 voto

What does that mean? If they're strings, fine -- you can have leading zeros. But if it's a number leading zeros are ignored, so printing or using 000003 will be just the same use using 3. So are you looking for a cell array? If so, see the FAQ: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F

3 comentarios

RuiQi
RuiQi el 11 de Dic. de 2016
Sorry it can be converted to a string. Id like to pad each element with zeros then store it in a cell. It can be of type string. I tried
a = {1 2 3 4 5};
b = sprintf('%06d',a{:});
but im still getting 000001000002.... even with %06c or %06s
RuiQi
RuiQi el 11 de Dic. de 2016
training_set = cell(size(train,1),1);
for i=1:size(train,1)
training_set{i,1} = sprintf('%06d',train(i));
end
this works but im looking for a method without using the for loop if its possible
RuiQi
RuiQi el 11 de Dic. de 2016
b = sprintf('%06d',[a{:}]);
doesnt work as well

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 11 de Dic. de 2016

Comentada:

el 11 de Dic. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by