In this tutorial we will assume that you know how to create vectors
and matrices, know how to index into them, and know about loops. For
more information on those topics see one of our tutorials on vectors
(*Introduction to Vectors in Matlab*), matrices (*Introduction to Matrices in Matlab*), vector operations
(*Vector Functions*), loops (*Loops*), plotting
(*Plotting*), executable files (*Executable Files*), or
subroutines (*Subroutines*).

There are times when you want your code to make a decision. For example, if you are approximating a differential equation, and the rate of change is discontinuous, you may want to change the rate depending on what time step you are on.

Here we will define an executable file that contains an if statement.
The file is called by Matlab, and it constructs a second derivative
finite difference matrix with boundary conditions. There is a variable
in the file called *decision*. If this variable is less than 3, the
file will find and plot the eigen values of the matrix, if it is
greater than 3 the eigen values of the inverse of the matrix are found
and plotted, otherwise, the system is inverted to find an
approximation to *y’=sin(x)* according to the specified boundary
conditions.

There are times when you want certain parts of your program to be executed only in limited circumstances. The way to do that is to put the code within an “if” statement. The most basic structure for an “if” statement is the following:

```
if (condition statement)
(matlab commands)
end
```

More complicated structures are also possible including combinations like the following:

```
if (condition statement)
(matlab commands)
elseif (condition statement)
(matlab commands)
elseif (condition statement)
(matlab commands)
.
.
.
else
(matlab commands)
end
```

The conditions are boolean statements and the standard comparisons can be made. Valid comparisons include “<” (less than), “>” (greater than), “<=” (less than or equal), “>=” (greater than or equal), “==” (equal - this is two equal signs with no spaces betweeen them), and “=” (not equal). For example, the following code will set the variable j to be -1:

```
a = 2;
b = 3;
if (a<b)
j = -1;
end
```

Additional statements can be added for more refined decision making. The following code sets the variable j to be 2.

```
a = 4;
b = 3;
if (a<b)
j = -1;
else if (a>b)
j = 2;
end
```

The else statement provides a catch all that will be executed if no
other condition is met. The following code sets the variable *j* to be
3.

```
a = 4;
b = 4;
if (a<b)
j = -1;
else if (a>b)
j = 2;
else
j = 3
end
```

This last example demonstrates one of the bad habits that Matlab
allows you to get away with. With finite precision arithmetic two
variables are rarely exactly the same. When using C or FORTRAN you
should never compare two floating numbers to see if they are the same.
Instead you should check to see if they are **close**. Matlab does not
use integer arithmetic so if you check to see if two numbers are the
same it **automatically** checks to see if the variables are close .
If you were to use C or FORTRAN then that last example could get you
into big trouble. but Matlab does the checking for you in case the
numbers are just really close.

Matlab allows you to string together multiple boolean expressions
using the standard logic operators, & (and) , | (or) , and ~
(not). For example to check to see if *a* is less than *b* and at the
same time *b* is greater than or equal to *c* you would use the
following commands:

```
if (a < b) & (b >= c)
Matlab commands
end
```

If you are not familiar with creating exectable files see our tutorial
on the subject (*Executable Files*). Otherwise, copy the following
script into a file called `ifDemo.m`.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | ```
decision = 3;
leftx = 0;
rightx = 1;
lefty = 1;
righty = 1;
N= 10;
h = (rightx-leftx)/(N-1);
x = [leftx:h:rightx]';
A = zeros(N);
for i=2:N-1,
A(i,i-1:i+1) = [1 -2 1];
end
A = A/h^2;
A(1,1) = 1;
A(N,N) = 1;
b = sin(x);
b(1) = lefty;
b(N) = righty;
if(decision<3)
% Find and plot the eigen values
[e,v] = eig(A);
e = diag(e);
plot(real(e),imag(e),'rx');
title('Eigen Values of the matrix');
elseif(decision>3)
% Find and plot the eigen values of inv(A)
[e,v] = eig(inv(A));
e = diag(e);
plot(real(e),imag(e),'rx');
title('Eigen Values of the inverse of the matrix');
else
% Solve the system
y = A\b;
linear = (lefty-righty+sin(leftx)-sin(rightx))/(leftx-rightx);
constant = lefty + sin(leftx) - linear*leftx;
true = -sin(x) + linear*x + constant;
subplot(1,2,1);
plot(x,y,'go',x,true,'y');
title('True Solution and Approximation');
xlabel('x');
ylabel('y');
subplot(1,2,2);
plot(x,abs(y-true),'cx');
title('Error');
xlabel('x');
ylabel('|Error|');
end
``` |

You can execute the instructions in the file by simply typing *ifDemo*
at the matlab prompt. Try changing the value of the variable
*decision* to see what actions the script will take. Also, try
changing the other variables and experiment.

The basic form of the *if*-block is demonstrated in the program above.
You are not required to have an *elseif* or *else* block, but you are
required to end the *if*-block with the *endif* statement.

Matlab Tutorial by Kelly Black is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Based on a work at http://www.cyclismo.org/tutorial/matlab/.

This page generated using Sphinx.