位置:首页 > 高级语言 > Matlab在线教程 > MATLAB关系运算

MATLAB关系运算

关系运算符标和非标量数据上也能正常工作。关系运算符对数组进行元素元素元素设置为逻辑1(真)的关系是真实的和元素设置为逻辑0(假),它是两个阵列,并返回一个同样大小的逻辑阵列之间的比较。

以下的表格显示的关系运算符:

操作符 描述
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to

例子

创建一个脚本文件,并键入下面的代码:

a = 100;
b = 200;
if (a >= b)
max = a
else
max = b
end

当运行该文件,它会产生以下结果:

max =
   200

除了在上述的关系运算符,MATLAB提供下列命令/函数用于同样的目的:

函数 描述
eq(a, b) Tests whether a is equal to b
ge(a, b) Tests whether a is greater than or equal to b
gt(a, b) Tests whether a is greater than b
le(a, b) Tests whether a is less than or equal to b
lt(a, b) Tests whether a is less than b
ne(a, b) Tests whether a is not equal to b
isequal Tests arrays for equality
isequaln Tests arrays for equality, treating NaN values as equal

例子

创建一个脚本文件,并键入下面的代码:

% comparing two values
a = 100;
b = 200;
if (ge(a,b))
max = a
else
max = b
end
% comparing two different values
a = 340;
b = 520;
if (le(a, b))
disp(' a is either less than or equal to b')
else
disp(' a is greater than b')
end

当运行该文件,它会产生以下结果:

max =
   200
 a is either less than or equal to b