主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

if, elseif, else

R2026a

条件为 true 时执行语句

语法

if expression
    statements
elseif expression
    statements
else
    statements
end

描述

if expression, statements, end 计算表达式并在表达式为 true 时执行一组语句。表达式的结果非空并且仅包含非零元素(逻辑值或实数值)时,该表达式为 true。否则,表达式为 false。

elseif 和 else 模块是可选的。这些语句仅在 if...end 块中前面的表达式为 false 时才会执行。if 块可以包含多个 elseif 块。

示例

示例

全部折叠

创建一个由 1 组成的矩阵。

nrows = 4;
ncols = 6;
A = ones(nrows,ncols);

遍历矩阵并为每个元素指定一个新值。对主对角线赋值 2,对相邻对角线赋值 -1,对其他位置赋值 0。

for c = 1:ncols
    for r = 1:nrows
        
        if r == c
            A(r,c) = 2;
        elseif abs(r-c) == 1
            A(r,c) = -1;
        else
            A(r,c) = 0;
        end
        
    end
end
A
A = 4×6

     2    -1     0     0     0     0
    -1     2    -1     0     0     0
     0    -1     2    -1     0     0
     0     0    -1     2    -1     0

在数组中包含关系运算符的表达式(例如 A > 0)仅在结果中的每个元素都为非零时才为 true。

使用 any 函数测试任何结果是否为 true。

limit = 0.75;
A = rand(10,1)
A = 10×1

    0.8147
    0.9058
    0.1270
    0.9134
    0.6324
    0.0975
    0.2785
    0.5469
    0.9575
    0.9649

if any(A > limit)
    disp('There is at least one value above the limit.')
else
    disp('All values are below the limit.')
end
There is at least one value above the limit.

使用 isequal 而不是 == 运算符比较数组来测试相等性,因为当数组的大小不同时 == 会导致错误。

创建两个数组。

A = ones(2,3);
B = rand(3,4,5);

如果 size(A) 与 size(B) 相同,则会串联这两个数组;否则显示一条警告并返回一个空数组。

if isequal(size(A),size(B))
   C = [A; B];
else
   disp('A and B are not the same size.')
   C = [];
end
A and B are not the same size.

使用 strcmp 比较字符向量。当字符向量的大小不同时,使用 == 测试相等性会产生错误。

reply = input('Would you like to see an echo? (y/n): ','s');
if strcmp(reply,'y')
  disp(reply)
end

确定值是否为非零值。使用 ~= 运算符测试不等式。

x = 10;
if x ~= 0
    disp('Nonzero value')
end
Nonzero value

确定值是否在指定范围内。

x = 10;
minVal = 2;
maxVal = 6;

if (x >= minVal) && (x <= maxVal)
    disp('Value within specified range.')
elseif (x > maxVal)
    disp('Value exceeds maximum value.')
else
    disp('Value is below minimum value.')
end
Value exceeds maximum value.

详细信息

全部折叠

提示

  • 您可以嵌套任意数量的 if 语句。每个 if 语句需要一个 end 关键字。

  • 避免在 elseif 关键字 (else if) 内于 else 之后添加空格。空格会创建嵌套的 if 语句,该语句要求独立的 end 关键字。

扩展功能

全部展开

C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。

GPU 代码生成
使用 GPU Coder™ 为 NVIDIA® GPU 生成 CUDA® 代码。

版本历史记录

在 R2006a 之前推出