Add 0 at end of double
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Stephen23
el 13 de Jul. de 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 comentarios
Stephen23
el 13 de Jul. de 2016
Editada: Stephen23
el 13 de Jul. de 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
el 13 de Jul. de 2016
S={'25521' '45674' '45618' '29466' '3346' '36024' '5082' '47221' '42987'}
S=cellfun(@(x) str2num([x repmat('0',1,5-numel(x))]),S)
0 comentarios
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!