Add 0 at end of double
5 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Stephen23
on 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 Comments
Stephen23
on 13 Jul 2016
Edited: Stephen23
on 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:
Azzi Abdelmalek
on 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)
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!