MATLAB: Day_diff calculate the difference in days between two peoples birthdays in 2015

dateshomeworkMATLAB

I have a problem to solve:
4. Write a function called day_diff that takes four scalar positive integer inputs, month1, day1, month2, day2. These represents the birthdays of two children who were born in 2015. The function returns a positive integer scalar that is equal to the difference between the ages of the two children in days. Make sure to check that the input values are of the correct types and they represent valid dates. If they are erroneous, return -1. An example call to the function would be >> dd = day_diff(1,30,2,1); 2 which would make dd equal 2. You are not allowed to use the built-in function datenum or datetime. Hint: store the number of days in the months of 2015 in a 12-element vector (e.g., 31, 28, 31, 30 …) and use it in a simple formula
my code is
function a = day_diff(month1, day1 , month2 , day2)
month(1:12) = [31 28 31 30 31 30 31 31 30 31 30 31];
a = abs(sum(month(month1:month2)) - day1 - (month(month2)-day2));
however for the problem day_diff(2,29,1,22) the solution is incorrect, I'm not sure if this is as the second month shouldn't have a 29th day or something. Any help greatly appreciated. Thanks!

Best Answer

"... Make sure to check that the input values are of the correct types and they represent valid dates ..."
Based on the wording of the assignment, I would assume you are to disallow month and day numbers that do not match an actual calendar date. Since 2015 is not a leap year, there is no Feb 29. You need to add code up front to check to see that the month numbers are integers between 1 and 12, and the day numbers are integers between 1 and the number of days in the particular month involved. You also need to ask yourself what happens if the first month is greater than the second month, and if your code correctly handles that situation. I.e., what does month(month1:month2) yield when month1 > month2?