How to pad all numbers in array ?

2 ビュー (過去 30 日間)
RuiQi
RuiQi 2016 年 12 月 11 日
コメント済み: RuiQi 2016 年 12 月 11 日
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 件のコメント
Stephen23
Stephen23 2016 年 12 月 11 日
編集済み: Stephen23 2016 年 12 月 11 日
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

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

採用された回答

Stephen23
Stephen23 2016 年 12 月 11 日
b = sprintf(' %06d',a{:});
^ add this space
  3 件のコメント
Stephen23
Stephen23 2016 年 12 月 11 日
編集済み: Stephen23 2016 年 12 月 11 日
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 2016 年 12 月 11 日
wow sprintfc works very nicely. and i will also read through the cellfun

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2016 年 12 月 11 日
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 件のコメント
RuiQi
RuiQi 2016 年 12 月 11 日
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 2016 年 12 月 11 日
b = sprintf('%06d',[a{:}]);
doesnt work as well

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by