Add 0 at end of double

3 Ansichten (letzte 30 Tage)
hdiba
hdiba am 13 Jul. 2016
Bearbeitet: Stephen23 am 13 Jul. 2016
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

Antworten (2)

Stephen23
Stephen23 am 13 Jul. 2016
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 Kommentare
Azzi Abdelmalek
Azzi Abdelmalek am 13 Jul. 2016
Which means the cell array was already a string
Stephen23
Stephen23 am 13 Jul. 2016
Bearbeitet: Stephen23 am 13 Jul. 2016
@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:

Melden Sie sich an, um zu kommentieren.


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

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by