MATLAB嵌套if语句||MATLAB switch语句

MATLAB嵌套if语句

在MATLAB中嵌套if语句始终是合法的,也就是说可以使用一个嵌套的 if-else语句 if 或 elseif 语句在另一个 if 或 elseif 语句。

MATLAB嵌套 if 语句语法:

详细语法如下:

if 
% Executes when the boolean expression 1 is true 
   if 
      % Executes when the boolean expression 2 is true    
  end
end

可以嵌套 elseif 或其他类似的方式,因为已经嵌套 if 语句。

详细例子如下:

在MATLAB中建立一个脚本文件,并输入下面的代码:

a = 100;
b = 200;
    % check the boolean condition 
   if( a == 100 )
   
       % if condition is true then check the following 
       if( b == 200 )
       
          % if condition is true then print the following 
          fprintf('Value of a is 100 and b is 200
' );
       end
       
   end
   fprintf('Exact value of a is : %d
', a );
   fprintf('Exact value of b is : %d
', b );

运行该文件,它显示的结果如下:

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

MATLAB switch语句

MATLAB中 switch 块有条件地执行一组语句,这些语句是从几个选项里选择执行的,其中每个选项涵盖了一个 case 语句。

请记住:

  • 计算 switch_expression 是一个标量或字符串。
  • 计算 case_expression 是标量,标量或字符串的字符串或单元阵列。

switch 块的功能是测试每个 case ,直到被测试的其中一个 case 是 true 。

case 是 true 的情况如下:

  • 对于数字,eq(case_expression,switch_expression).

  • 对于字符串,strcmp(case_expression,switch_expression).

  • 对于对象,支持 eq 函数,eq(case_expression,switch_expression).

  • 对于单元阵列case_expression的,在单元阵列与switch_expression相匹配的元素中的至少一个,如上文所定义的数字,字符串和对象。

当上述有一个情况是 true,MATLAB 就执行与之相应的语句,然后不再执行以后的语句,直接退出 switch 块。

otherwise 块是可选的,任何情况下,只有当真正执行。

MATLAB switch语句语法

在MATLAB 中 switch 语句的语法如下:

switch 
   case 
     
   case 
     
     ...
     ...
   otherwise
       
end

详细例子

在MATLAB中建立一个脚本文件,并输入下述代码:

n = input('Enter a number: ');

switch n
    case -1
        disp('negative one')
    case 0
        disp('zero')
    case 1
        disp('positive one')
    otherwise
        disp('other value')
end

在命令提示符下,输入数字 1,输出结果为:

positive one

重复执行该代码并输入数字 3,输出结果为:

other value

你可能感兴趣的:(matlab入门教程,matlab,java,数据结构,算法)