【问题标题】:MATLAB 'continue' command alternativeMATLAB“继续”命令替代
【发布时间】:2018-08-05 08:58:06
【问题描述】:
for i = 1:30
    if condition1
        statement1
    elseif condition2
        continue
    else
        statement2
    end
    statement3
end

如上所述,如果满足条件 2,我在 for 循环中有“继续”命令跳过“语句 3”。这段代码运行良好。 但是当我必须运行 if-else 部分进行测试时,它会出错,因为“继续”应该在 for/while 循环中运行。

有没有办法在 for 循环中做同样的事情(什么都不做,跳到下一次迭代),但也可以单独工作?

【问题讨论】:

  • 测试的时候可以简单注释continue这行吗?

标签: matlab for-loop continue


【解决方案1】:

如果你想在循环外运行完全相同的代码,因此无法使用continue,你可以简单地重写如下:

if ~condition2
    if condition1
        statement1
    else
        statement2  
    end

    statement3
end

或者(我知道它不是很优雅,但确实有效):

if condition1
    statement1
    statement3
elseif condition2
else
    statement2  
    statement3
end

上面的代码可以通过重写来改进(很多):

if condition1
    statement1
    statement3
elseif ~condition2
    statement2  
    statement3
end

最后,如果你的statement3特别长,不想重复两次,你可以使用绕过标志进一步改进上面的代码:

go3 = false;

if condition1
    statement1
    go3 = true;
elseif ~condition2
    statement2  
    go3 = true;
end

if go3
    statement3
end

问题是抽象的条件不允许我充分发挥我的想象力。也许如果您指定您使用的条件,即使以简化的方式,我也可以尝试提出更好的解决方案。

【讨论】:

    【解决方案2】:

    首先,您所写的内容如您所愿。例如检查此代码:

    for i = 1:7
        if i<=2
            disp([num2str(i) ' statement1'])
        elseif i>=4 &&  i<=6
            disp([num2str(i) ' only continue here'])
            continue
        else       
            disp([num2str(i) ' statement2'])
        end
        disp([num2str(i) ' statement3']);
    end
    disp('yeah')
    
    
    >>
    1 statement1
    1 statement3
    2 statement1
    2 statement3
    3 statement2
    3 statement3
    4 only continue here
    5 only continue here
    6 only continue here
    7 statement2
    7 statement3
    yeah
    

    其次,你也可以这样做

    for i=1:30
        if condition1
            statement1
            statement3
        elseif condition2
            continue
        else
            statement2  
            statement3
        end
    end
    

    【讨论】:

    • 最后一个代码块有一个悬空的endif 语句是否意外遗漏了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2015-08-19
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    相关资源
    最近更新 更多