1. Skip to content

      if, elseif, else

      Execute statements if condition is true

      Syntax

      if expression    statementselseif expression    statementselse    statementsend

      Description

      example

      if expression, statements,end evaluates an expression,and executes a group of statements when the expression is true. Anexpression is true when its result is nonempty and contains only nonzeroelements (logical or real numeric). Otherwise, the expression is false.

      The elseif and else blocksare optional. The statements execute only if previous expressionsin the if...end block are false. An if blockcan include multiple elseif blocks.

      Examples

      collapse all

      Create a matrix of 1s.

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

      Loop through the matrix and assign each element a new value. Assign 2 on the main diagonal, -1 on the adjacent diagonals, and 0 everywhere else.

      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            endendA
      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

      Expressions that include relational operators on arrays, such as A > 0, are true only when every element in the result is nonzero.

      Test if any results are true using the any function.

      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.

      Compare arrays using isequal rather than the == operator to test for equality, because == results in an error when the arrays are different sizes.

      Create two arrays.

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

      If size(A) and size(B) are the same, concatenate the arrays; otherwise, display a warning and return an empty array.

      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.

      Use strcmp to compare character vectors.Using == to test for equality results in an errorwhen the character vectors are different sizes.

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

      Determine if a value is nonzero. Use the ~= operator to test for inequality.

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

      Determine if a value falls within a specified range.

      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.

      More About

      collapse all

      Expression

      An expression can include relational operators(such as < or ==) and logicaloperators (such as &&, ||,or ~). Use the logical operators and and or tocreate compound expressions. MATLAB® evaluates compound expressionsfrom left to right, adhering to operator precedence rules.

      Within the conditional expression of an if...end block,logical operators & and | behaveas short-circuit operators. This behavior is the same as && and ||,respectively. Since && and || consistentlyshort-circuit in conditional expressions and statements, it is goodpractice to use && and || insteadof & and | within the expression.For example,

      x = 42;if exist('myfunction.m','file') && (myfunction(x) >= pi)    disp('Expressions are true')end

      The first part of the expression evaluates to false. Therefore, MATLAB doesnot need to evaluate the second part of the expression, which wouldresult in an undefined function error.

      Tips

      • You can nest any number of if statements.Each if statement requires an end keyword.

      • Avoid adding a space after else withinthe elseif keyword (else if).The space creates a nested if statement that requiresits own end keyword.

      Extended Capabilities

      C/C++ Code Generation
      Generate C and C++ code using MATLAB® Coder™.

      Introduced before R2006a

      1. http://www.rvp04kb1.tw | http://m.rvp04kb1.tw | http://wap.rvp04kb1.tw | http://3g.rvp04kb1.tw | http://4g.rvp04kb1.tw | http://5g.rvp04kb1.tw | http://mobile.rvp04kb1.tw | http://vip.rvp04kb1.tw | http://ios.rvp04kb1.tw | http://anzhuo.rvp04kb1.tw | http://fc220c.rvp04kb1.tw | http://6.rvp04kb1.tw | http://4c2.rvp04kb1.tw | http://42f.rvp04kb1.tw | http://c244.rvp04kb1.tw | http://24ea.rvp04kb1.tw | 60岁老头一夜7次