Skip to Main Content Skip to Search
Product Documentation

elseif - Optional keyword within an if statement

Syntax

if expression
   statements
elseif expression
   statements
else
   statements
end

Description

An if statement evaluates an expression, and executes a group of statements when the expression is true.

elseif and else are optional, and execute only when previous expressions in the if statement are false.

For more information about valid expressions and when they are true, see the if reference page.

Tips

Examples

Assign to a matrix values that depend on their indices:

% Preallocate a matrix
nrows = 10;
ncols = 10;
myData = ones(nrows, ncols);

% Loop through the matrix
for r = 1:nrows
   for c = 1:ncols

      if r == c
         myData(r,c) = 2;
      elseif abs(r - c) == 1
         myData(r,c) = -1;
      else
         myData(r,c) = 0;
      end

   end
end

See Also

end | for | if | switch | while

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS