How can I transform a number to string with space using num2str?

What is the result of "num2str(1,'%2d')"? I think it should be " 1", but the results is "1". I mean there is no space before "1". Actually, the result of "num2str(1,'%02d')" is "01", and the result of "num2str(1,'%-2d')" is "1". And, the result of "sprintf('%2d',1)" is " 1".
How can I transform a number to string with space using num2str?

 採用された回答

Simon
Simon 2013 年 12 月 9 日

0 投票

Hi!
Maybe this way?
num = [1000; 1001];
% numeric part
numpart = arrayfun(@(x) sprintf('%2d', mod(x,100)), num, 'UniformOutput', false);
% letter part
letterpart = char(mod(num,26*100)./100+65);
% concat everything
retsult = strcat(letterpart, numpart)

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2013 年 12 月 5 日

1 投票

Use sprintf instead of nu2str()
sprintf('%2d', 1)

3 件のコメント

Jung-Woo
Jung-Woo 2013 年 12 月 5 日
If it is the single number, sprintf will be OK. But, what if it is an array? num2str([1;2],'%2d') is "1;2" and 2x1 char. num2str([1;11],'%2d') is " 1;11" and 2x2 char. sprintf('%2d\n',[1;11]) is " 1;11" and 1x6 char. The results of them are the same, but the dimension is different. As you see, if there is a 2-digit number in the array, there is space before the 1-digit number. But, if there is only 1-digit number in the array, there is no space.
Simon
Simon 2013 年 12 月 5 日
Hi!
Please compare
sprintf('%2d\n',[1;11])
and
sprintf('%d\n',[1;11])
Walter Roberson
Walter Roberson 2013 年 12 月 9 日
numt = num(:).'; %make sure it is row vector
rem100 = mod(numt, 100);
lead2600 = mod((numt - rem100) ./ 100, 26) + 65;
longstr = sprintf('%c%2d\n', [lead2600; rem100]);
strs = regexp(longstr, '\n', 'split');

サインインしてコメントする。

Jung-Woo
Jung-Woo 2013 年 12 月 9 日

1 投票

Let me ask another way. Actually, I am trying to convert some numbers to alphabatical ID including alphabet and 2 digit numbers.
For example,
num = [1000; 1011];
cellstr([char(mod(num,26*100)./100+65),num2str(mod(num,100),'%2d')])
ans =
'K 0'
'K11'
That is what I want to have. But, if num = [1000; 1001], the 2-digit numbers become just 1-digit numbers like:
num = [1000; 1001];
cellstr([char(mod(num,26*100)./100+65),num2str(mod(num,100),'%2d')])
ans =
'K0'
'K1'
Here, my question is how I can fix the number of digit to 2. My expectation is:
ans =
'K 0'
'K 1'

1 件のコメント

Walter Roberson
Walter Roberson 2013 年 12 月 9 日
You cannot use num2str() for this purpose. In situations in which every entry ends up with a leading blank, num2str() will strip off the leading blank.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

質問済み:

2013 年 12 月 5 日

コメント済み:

2013 年 12 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by