简体   繁体   English

将多个IF语句组合成一个(matlab)?

[英]Combining several IF statements into one (matlab)?

Would there be a way to combine several if statements to perform in the same sequence as below: 是否有一种方法可以组合多个if语句以按以下相同顺序执行:

X = [1 2 3 4; 5 4 6 7; 2 8 9 2];
X

n = length(X(1,:))-1;

for i=1:n,     
    if length(X(1,:)) == n,
    .........
    end

    if length(X(1,:)) == n-1,
    .........
    end

    if length(X(1,:)) == n-2,
    .........
    end
end

Any suggestions? 有什么建议么?

Judging from the code you provide, and the comment you gave Theodros, I think this is a case of code smell . 从您提供的代码以及您给Theodros的注释来看,我认为这是一种代码异常的情况。 In other words, I have a hunch there are deeper problems with your approach, which we might be able to improve upon if you disclose your full problem. 换句话说,我预感您的方法存在更深层次的问题,如果您公开您的全部问题,我们也许可以改善。

Now, having said that: if the operations you want to perform differ for each case, then obviously, you can't combine them into one statement. 现在,您已经说过:如果每种情况下要执行的操作都不同,那么显然,您无法将它们组合为一个语句。 If there are multple copies of the same procedures in each block, you can use logical OR: 如果每个块中都有相同过程的多个副本,则可以使用逻辑或:

if length(X(1,:)) == n || length(X(1,:)) == n-1
    ...
end

if length(X(1,:)) == n-2 || length(X(1,:)) == n-4
    ...
end

The code will look nicer (and be slightly faster) if you use the switch statement, as @TheodrosZelleke suggested. 如@TheodrosZelleke所建议,如果使用switch语句,代码将看起来更好(并且会更快)。 Combining cases goes like this: 合并情况如下:

switch length(X(1,:))

    case {1 2}  %# length == 1 OR length == 2
        ...
    case {3 4}  %# length == 3 OR length == 4
        ...
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM