How can I add leading zeros in a column vector?

2 views (last 30 days)
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 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 10 Jun 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 on 10 Jun 2016
Edited: James Condie on 10 Jun 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.

Sign in to comment.

Accepted Answer

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

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 10 Jun 2016
sprintf(['%0',sprintf('%d',max(ceil(log10(X)))),'d\n'],X)
  1 Comment
James Condie
James Condie on 10 Jun 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?

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!