首页 > 解决方案 > 在 Matlab 中获得两个输出而不是一个

问题描述

这里的问题是在不使用原生 Matlab 日期函数的情况下确定提供的日期是否有效。我希望有人能在这里指出我的错误。当我提交它时,我还在 Matlab 学习工具中收到“valid在调用期间未分配输出参数(可能还有其他参数) ”错误。valid_date

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

标签: matlabdate

解决方案


在 Matlab 函数结束时返回时,变量的值valid作为输出发送。在四个注释下面的行中,您需要在 if 语句中将变量分配为 true 或 false。例如:

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

推荐阅读