The question here was to find if the date provided is a valid one or not without using native Matlab date functions. I was hoping if someone can point out my mistake here. I'm also getting the "Output argument valid
(and maybe others) not assigned during call to valid_date
" error in Matlab learning tool when I submit it.
function valid = valid_date(year,month,day)
if nargin~=3
valid = false;
elseif ~isscalar(year)||year<1||year~=fix(year)
valid = false;
return
elseif ~isscalar(month)||month<1||month~=fix(month)
valid = false;
return
elseif ~isscalar(day)||day<1||day~=fix(day)
valid = false;
return
elseif month>12 || day > 31
valid = false;
end
if ((mod(year,4)==0 && mod(year,100)~=0) || mod(year,400)==0)
leapdata=1;
else
leapdata=0;
end
%the below if statements are used to define the months. Some months have
%31 days and others have 30 days, while February has only 28 days and 29 on
%leap years. this is checked in the below code.
% I feel the below code is where the error is.
if ismember (month, [1 3 5 7 8 10 12])
ismember (day, (1:31))
return
elseif ismember( month, [4 6 9 11])
ismember (day, (1:30))
return
end
if month == 2
if leapdata==1
ismember (day, (1:29))
return
elseif leapdata==0
ismember (day, (1:28))
return
else
valid = false;
end
end
When returning at the end of a Matlab function, the value of the variable valid
is sent as an output. In the lines below the four comments, you need to assign the variable to true or false inside of the if statements. For example:
if ismember(month, [1 3 5 7 8 10 12])
valid = ismember(day, (1:31))
return
elseif ismember(month, [4 6 9 11])
valid = ismember(day, (1:30))
return
end
if month == 2
if leapdata == 1
valid = ismember(day, (1:29))
return
elseif leapdata == 0
valid = ismember(day, (1:28))
return
else
valid = false;
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.