How can I to convert a cell to a double without losing the leading zeros?

조회 수: 38 (최근 30일)
I have a loop where I am trying to extract the numbers and convert them to double. However, when the numbers are "0000", the result is just "0". How can I do this?
for x = 1:length(ix20);
namex = files(i).name;
sss=regexp(namex, '(?:\d{4})\>','match');
format longg;
hm(x)=str2double(sss);
end
  댓글 수: 2
David Hill
David Hill 2020년 9월 20일
I don't understand what you are trying to do. Please explain with an example (input and expected output). The double of '0000' is 0.
pink flower
pink flower 2020년 9월 20일
This is an hour and minute data. I need to put them in an array, so I'm trying to do this cell to double transformation.

댓글을 달려면 로그인하십시오.

채택된 답변

Star Strider
Star Strider 2020년 9월 20일
Thank you for quoting my code from Extracting numbers from mixed string !
It is not possible to retain leading zeros in a numeric representation, such as double. To retain leading zeros, they must be kept as character arrays (single quotes) or string variables (double quotes).
I would appreciate it if you would Accept my Answer that uses the regexp call you quoted!
.
  댓글 수: 2
pink flower
pink flower 2020년 9월 20일
This is an hour and minute data. I need to put them in an array, so I'm trying to do this cell to double transformation. Can I do this without losing 0000?
Star Strider
Star Strider 2020년 9월 20일
The leading zeros would disappear if your converted them to numeric values.
If you want to convert them to datetime arrays, that would be straightforward:
out = compose("%04d", 0:5:20).'
DT = datetime(out, 'InputFormat',"HHmm", 'Format','HH:mm')
producing:
out =
5×1 string array
"0000"
"0005"
"0010"
"0015"
"0020"
DT =
5×1 datetime array
00:00
00:05
00:10
00:15
00:20
The ‘DT’ vector would then be saved as a datetime array (call it anything you wish), with the leading zeros intact, and converted to hours and minutes as well. (The 'InputFormat' string specifies how the input is parsed, and the 'Format' string specifies how it is displayed.)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Cris LaPierre
Cris LaPierre 2020년 9월 20일
편집: Cris LaPierre 2020년 9월 20일
I believe you would have to keep it a string in order to pad with zeros up front. See this post.

카테고리

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