フィルターのクリア

Add 0 at end of double

3 ビュー (過去 30 日間)
hdiba
hdiba 2016 年 7 月 13 日
編集済み: Stephen23 2016 年 7 月 13 日
Hello, I have a vector of double values, that resulted from str2double. S= 25521 45674 45618 29466 3346 36024 5082 47221 42987 ... Now I would like to add a 0 to each value that has not 5 characters.. In the example it would be to 3346 and 5082, so I Have 33460 and 50820. Perhaps I have to convert the double values first do string again and add zero? thanks

回答 (2 件)

Stephen23
Stephen23 2016 年 7 月 13 日
You don't need to do any slow string conversions:
>> vec = [25521,45674,45618,29466,3346,36024,5082,47221,42987];
>> idx = log10(vec)<4;
>> vec(idx) = 10*vec(idx)
vec =
25521 45674 45618 29466 33460 36024 50820 47221 42987
  4 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 13 日
Which means the cell array was already a string
Stephen23
Stephen23 2016 年 7 月 13 日
編集済み: Stephen23 2016 年 7 月 13 日
@Azzi Abdelmalek: indeed the data was originally a cell of strings. However one str2double call and my code is faster than cellfun with num2str in an anonymous function. Here with 1e4 iterations:
Elapsed time is 9.170952 seconds. % your answer, with |cellfun|.
Elapsed time is 3.370354 seconds. % my answer, with |str2double|.
My answer also avoids using str2num, which calls eval. There is a warning message in the MATLAB editor advising to avoid str2num, because it is slow:
Test file here:

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


Azzi Abdelmalek
Azzi Abdelmalek 2016 年 7 月 13 日
S={'25521' '45674' '45618' '29466' '3346' '36024' '5082' '47221' '42987'}
S=cellfun(@(x) str2num([x repmat('0',1,5-numel(x))]),S)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by