Filter löschen
Filter löschen

MATLAB Cody Coursework Help

2 Ansichten (letzte 30 Tage)
Ian Connelly
Ian Connelly am 2 Mär. 2016
Kommentiert: Steven Lord am 2 Mär. 2016
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

Antworten (1)

Guillaume
Guillaume am 2 Mär. 2016
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 Kommentar
Steven Lord
Steven Lord am 2 Mär. 2016
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.)

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

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

Start Hunting!

Translated by