How to solve this error?
2 次查看(过去 30 天)
显示 更早的评论
Error for the Code is :
Operands to the || and && operators must be convertible to logical scalar values.
Error in valid_date (line 4)
if month==2 & day<=29 || month==[4,6,9,11] & day<=30 || month==[1,3,5,7,8,10,12] & day<=31
Where the Code is :
function valid = valid_date(year,month,day)
if isscalar(year) && year>0 && isscalar(month) && month<=12 && isscalar(day) && day>0
if mod(year,400)==0 || mod(year,100)~=0 && mod(year,4)==0
if month==2 & day<=29 || month==[4,6,9,11] & day<=30 || month==[1,3,5,7,8,10,12] & day<=31
valid = true;
elseif month==2 & day>29 || month==[4,6,9,11] & day>30 || month==[1,3,5,7,8,10,12] & day>31
valid = false;
end
else
valid = false;
end
else
valid = false;
end
0 个评论
采纳的回答
Rik
2020-5-27
You are close, but you forgot that the code below returns an array.
month==[4,6,9,11]
Use parantheses to group your coditions. That should also make it more clear that you don't need that elseif.
Consider create a variable to store the number of days in Feb. Currently your code will reject all non-leap years.
Also, you should replace all & and | by && and || as well.
4 个评论
Rik
2020-5-31
Those or statements don't do what you think they are doing. Your previous solution was closer, you only had to find a function that would check if any of the elements was true (hint: use the any function on that vector).
You should first try your code line by line. Is the output of every function what you expect? For the example you give, there is a valid date, but your code returns 0. Can you see why?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Time Series Objects 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!