Help! Indexing a Vector, Display Issues
3 views (last 30 days)
I asked a question earlier about this problem, and I have almost finished the code, but I am struggling with a couple more things that I have no clue (or experience with MATLAB) to solve. My problem is:
Create a script that asks the user repeatedly for two time intervals in the form of hours, minutes, and seconds, and provides the addition of these two time intervals in the same form. The script should end if the input from the user is zero for all six values. You should write a function which takes in the given time intervals and returns their addition. The script will handle the user input, call the function, and display the corresponding output.
I am, somehow, supposed to convert the time intervals so that, for example, if the total number of minutes entered by the user is 76 minutes, it will convert this to 1 hour and 16 minutes and add 1 hour to the “hours portion” of the vector and 16 to the “minutes portion” of the vector. This needs to happen for the “seconds portion” of the vector as well. I was thinking that I needed to index the vector somehow, but I am not sure how I can do that in this situation.
I also need to get my output to display as hms1 + hms2 = hmsTotal, which I have been struggling with for hours. I haven’t learned any techniques for this as of yet.
Here is my function code:
function [hmsTotal] = intervalAddition(hms1,hms2)
% This function adds the first and second time intervals input by the user.
hmsTotal = (hms1 + hms2);
Here is my main script:
flag = true;
disp('Do you want to enter a time interval?')
answer = input('Enter 1 for YES and 0 for NO :')
if answer == 1
hms1 = input("Enter the first time interval using 6 digits representing hours, minutes, and seconds in vector form: ");
hms2 = input("Enter the second time interval using 6 digits representing hours, minutes, and seconds in vector form: ");
if hms1 == 0 & hms2 == 0
flag = false;
hmsTotal = [hms1 + hms2];
flag = false;
Alan Moses on 29 Oct 2020
According to the script you have written, if the inputs are provided in the [h,m,s] format, direct addition can be done. Providing six digits as input needs a change in logic in computing the output.
To answer the second part of your question, check out fix and rem functions. The following piece of code may solve the issue assuming inputs to the function are provided in [h,m,s] format:
function hms_y = convertInterval(hms) %should be applied to both input vectors and output vector
h = hms(1)+fix(hms(2)/60); %adding hours if mins >= 60
m = rem(hms(2),60)+fix(hms(3)/60); %adding minutes if secs >= 60
s = rem(hms(3),60);
hms_y = [h,m,s];
Hope this helps!