MATLAB提供两种类型的逻辑运算符和函数:
- 逐元素 - 这些运算符对逻辑阵列的相应元素进行操作。
- 短路 - 这些运算符在标量和逻辑表达式上运行。
元素逻辑运算符在逻辑数组上运行逐个元素。符号&,|和〜是逻辑数组运算符AND,OR和NOT。
短路逻辑运算符允许逻辑运算短路。符号&&和||是逻辑短路运算符AND和OR。
示例
创建脚本文件并键入以下代码 -
a = 5;
b = 20;
if ( a && b )
disp('Line 1 - Condition is true');
end
if ( a || b )
disp('Line 2 - Condition is true');
end
% lets change the value of a and b
a = 0;
b = 10;
if ( a && b )
disp('Line 3 - Condition is true');
else
disp('Line 3 - Condition is not true');
end
if (~(a && b))
disp('Line 4 - Condition is true');
end
执行上面示例代码,得到以下结果 -
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
