How can I add leading zeros in a column vector?

2 次查看(过去 30 天)
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 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2016-6-10
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 2016-6-10
编辑:James Condie 2016-6-10
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.

请先登录,再进行评论。

采纳的回答

Azzi Abdelmalek
Azzi Abdelmalek 2016-6-10
v=[0 1 2 3 59 100 101]'
w=arrayfun(@(x) sprintf('%04d',x),v,'un',0)

更多回答(1 个)

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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by