필터 지우기
필터 지우기

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 CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by