How can I add leading zeros in a column vector?

2 visualizaciones (últimos 30 días)
James Condie
James Condie el 10 de Jun. de 2016
Comentada: Daniel Pare el 21 de Jul. de 2020
assuming X is my vertical vector of numbers, I've tried
X_with_zeros=sprintf('%04d\n',X)
It prints out what a want but saves it all combined in a 1x1 char array
I tried this loop:
j=length(length(X));
for i=1:j
X_with_zeros=zeros(j,1);
X_with_zeros(i,1)=X(sprintf('%04d',X(i)),1);
end
It's telling me that my assignment doesn't match the dimensions of the subscript, I've tried different ways. I realize I probably need different rules for a list of strings or char array.
  2 comentarios
Azzi Abdelmalek
Azzi Abdelmalek el 10 de Jun. de 2016
Your question is confusing, you start with leading zeros and end with date problem. Can you make your question clear. Post an example and explain what you want.
James Condie
James Condie el 10 de Jun. de 2016
Editada: James Condie el 10 de Jun. de 2016
thanks, i limited this to one question. Here's an example: I have a list of hours and minutes in a column vector like this
0
1
2
3
...
59
100
101
..
2359
0
etc. Id like to add padding so all entries have four digits padded with leading zeros so it looks like this
0000
0001
...
0059
0100
..
etc.

Iniciar sesión para comentar.

Respuesta aceptada

Azzi Abdelmalek
Azzi Abdelmalek el 10 de Jun. de 2016
v=[0 1 2 3 59 100 101]'
w=arrayfun(@(x) sprintf('%04d',x),v,'un',0)
  1 comentario
Daniel Pare
Daniel Pare el 21 de Jul. de 2020
Thanks, It works great and fast on table of more than 200k records.

Iniciar sesión para comentar.

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 10 de Jun. de 2016
sprintf(['%0',sprintf('%d',max(ceil(log10(X)))),'d\n'],X)
  1 comentario
James Condie
James Condie el 10 de Jun. de 2016
this prints out what I want, but when I assign this to variable it still saves it as a big character in a 1x1 variable, maybe I need to assign it to something different?

Iniciar sesión para comentar.

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