필터 지우기
필터 지우기

MATLAB Cody Coursework Help

조회 수: 2 (최근 30일)
Ian Connelly
Ian Connelly 2016년 3월 2일
댓글: Steven Lord 2016년 3월 2일
Hey, So I'm working on some MATLAB homework where I am given two strings in "HH:MM:SS" format and I need to find the difference of the two strings in minutes. The code that I have written passes a majority of the tests in Cody Coursework, but for some reason can't pass the third test. Does anyone have any suggestions on where my code is incorrect?
function elapsed = elapsed_time(d1,d2)
D1 = datevec(d1, 'HH MM SS');
D2 = datevec(d2, 'HH MM SS');
sum1 = (D1(4)*60) + D1(5) + (D1(6)*0.016667);
sum2 = (D2(4)*60) + D2(5) + (D2(6)*0.016667);
elapsed = (abs(sum1-sum2));
end
Any help would be nice, thanks in advance

답변 (1개)

Guillaume
Guillaume 2016년 3월 2일
I'd use datetime instead of datevec. It makes this sort of calculations much easier:
elapsed = minutes(datetime(d2, 'InputFormat', 'HH mm ss') - ...
datetime(d1, 'InputFormat', 'HH mm ss')); %note the difference in format string
As we don't know what your 3rd test is, we can only speculate on the cause of failure. I would suspect it's because 0.016667 is only a crude approximation of 1/60, and for some values the difference is enough to put you over the accuracy threshold required by the test.
You gain nothing by using a multiplication by 0.016667 and it actually makes your code more obscure as the reader now has to check that 0.016667 is a correct approximation for 1/60, so what don't you write it as a division. Makes a lot more sense to me:
m = d(4)*60 + d(5) + d(6)/60; %is a lot more accurate and it's that you're converting seconds into minutes
  댓글 수: 1
Steven Lord
Steven Lord 2016년 3월 2일
Alternately, convert the two times into a number of seconds (so there's no division involved in the conversions.) Compute the difference between the two times in seconds. Finally convert the difference in seconds into minutes (so there's just one division.)

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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by