【问题标题】:Getting two outputs instead of one in Matlab在 Matlab 中获得两个输出而不是一个
【发布时间】:2021-05-15 23:30:33
【问题描述】:

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

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

【问题讨论】:

  • 请从基础开始:mathworks.com/help/matlab/matlab_prog/… — 通过反复试验学习编程没有必要令人沮丧,跳过基础知识会让你走上痛苦的道路。
  • 您忘记在多次退货中分配valid 值。另外,我建议您发布整个错误,以便更清楚地了解错误发生的位置
  • @CrisLuengo,这实际上是基础课程中的一个问题。的确,通过反复试验来做到这一点非常令人沮丧,周六我被困在这个问题上将近 9 个小时:/

标签: matlab date


【解决方案1】:

在 Matlab 函数结束时返回时,变量valid 的值作为输出发送。在四个 cmets 下面的行中,您需要在 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

【讨论】:

  • 感谢您的建议,不幸的是,我仍然得到双输出:(
  • @BungyCord 您需要了解函数的输出与函数写入控制台的内容之间的区别。检查末尾没有分号的行(提示:此答案中有 4 段代码)。请务必使用 MATLAB 编辑器,并注意它给您的警告。它确实在缺少分号的情况下警告这些行。
  • @CrisLuengo,哦,该死的,我的错。错过了检查编辑器。双输出已停止,但得到错误的结果。尽管如此,我相信我能够找到错误。非常感谢:D
猜你喜欢
  • 2021-07-28
  • 2016-06-03
  • 1970-01-01
  • 2019-10-24
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多