hh:mm:ss string to duration type

조회 수: 13 (최근 30일)
Jason Nicholson
Jason Nicholson 2016년 1월 11일
댓글: Jason Nicholson 2016년 1월 11일
I have strings that look like this: '24:06:26' and '7:20:26'. I want a duration type. What is the best way to get this?
All I have right now is
str = ' 7:20:26' % or '24:06:26'
d = duration(cellfun(@(x) str2double(x), regexp(str,'\d{1,2}','match')));
This seems inefficient and overkill because I have to use at least 3 function calls to get to a duration type.

채택된 답변

Guillaume
Guillaume 2016년 1월 11일
You can get rid of the cellfun call, str2double works directly on cell arrays. The other two functions are necessary in any case. datetime just hides the string splitting and string to number conversion in its constructor.
You could use strsplit instead of regexp. I'm not sure which would be more efficient:
d = duration(str2double(strsplit(str, ':')));
  댓글 수: 1
Jason Nicholson
Jason Nicholson 2016년 1월 11일
This is definitely an improvement. I am going wait another day. If I don't get a better answer, then I will accept this one.

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

추가 답변 (0개)

카테고리

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