使用逻辑条件在 matlab 中编程

Programming in matlab with logical conditions

我有一个小逻辑问题,希望有一天能解决!! 假设您有 4 个变量,我称它们为 a、b、c 和 d。 现在基于一些逻辑给出以下条件。

程序通过:

程序失败:

因此,如果您填写一个变量,您将被迫填写更多。如果您不填写任何变量,则无需任何操作。

为了简单起见,我说 1 等于填充,0 等于未填充。我的代码无法正常工作,因为如果我说只有 d 被填充,它就会返回这是可以的。但它不应该工作,因为只有 d 是失败的。

知道我能做什么吗?也许我的思考方式不正确?请记住,0 和 1 只是为了保持简单,所以加和没有帮助!

这是我的代码:

a = 0; 
b = 0; 
c = 0; 
d = 1; 

if a ~=0 || b ~=0 || c ~=0 || d ~=0
    if ~(a~=0 || b~=0 && c~=0 || d~=0 ) 
       works = 1;
    else
       no = 1;
    end
end 

感谢阅读!

如果你想让你的代码更具可读性,你可以使用一种方法来做逻辑,最简单的方法就是翻译你的逻辑。

public static boolean isParamFilled(boolean a, boolean b, boolean c, boolean d) {
    if ((a || b) && (c || d)) return true;
    if (c && d) return true;
    int ia = a ? 1 : 0;
    int ib = b ? 1 : 0;
    int ic = c ? 1 : 0;
    int id = d ? 1 : 0;
    // Only one of the 4 parameters is filled.
    if (ia + ib + ic + id == 1) return true;
    if (a && b) return false;
    // default value
    return false;
}

public static void main(String...args) {
    boolean a = false; 
    boolean b = false; 
    boolean c = false; 
    boolean d = true; 

    booledan worked = isParamFilled(a, b, c, d);
}

因为题目是MATLAB,所以我也给你一个MATLAB的解法。基本上你的加和的想法只是要走的路,只需先将你的变量转换为二进制,这是用 logical 完成的。因此可以使用

来检查是否失败
arr = logical([a,b,c,d]);
fail = sum(logical(arr))==1 || all(arr(1:2))

第一个条件检查已填充的数量,第二个条件检查 ab 是否都已设置。

需要注意的是,存在同时满足通过和失败条件的情况(例如所有变量集)。上面的解决方案是贪婪的。传递贪婪的解决方案是(正如 Cris Luengo 在评论中提出的那样)

arr = logical([a,b,c,d]);
fail = sum(logical(arr))==1 || all(arr==[1,1,0,0])