Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Help with call function in Matlab. I wrote a program to calculate how many years

ID: 3566977 • Letter: H

Question

Help with call function in Matlab.

I wrote a program to calculate how many years and months old you are. How can I implement 1 call function to do the year and month calculation?

clc

clear

cY = input('Enter today''s 4-digit year: ');

cM = input('Enter today''s month number: ');

bY = input('Enter the 4-digit year of your birth: ');

bM = input('Enter the month number of your birth: ');

if cM > bM

fprintf(' You are %d years and %d months old. ', (cY-bY), (cM-bM));

else

fprintf(' You are %d years and %d months old. ', (cY-bY-1), (cM-bM+12));

end

Explanation / Answer

I used datenum for converting the input to a serial date number. Then subtract now, and use datestr which converts the result back to a readable string in a desired 'DD/MM/YYYY' format.
Method- 1:
As you can see, you should use 'mm' instead of 'MM' ('MM' corresponds to 'minutes' instead of 'months'.
str='19/12/1992';
birth_numdate=datenum(str,'DD/mm/YYYY');
myage=datestr(now-birth_numdate,'DD/mm/YYYY');
Method-2:
Use datevec, which would give you a vector containing #years, months, days, hours, minutes and seconds:
str='19/12/1992';
birth_numdate=datenum(str,'DD/mm/YYYY');
myage=datestr(now-birth_numdate,'DD/mm/YYYY');
vec_myage=datevec(now-birth_numdate);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote