Wednesday, 9 February 2011

The If Statement(matlab tutorial)

The If Statement

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, matrices, vector operations, loops, plotting, executable files, or 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;
elseif (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;
elseif (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


Example

If you are not familiar with creating exectable files see our tutorial on the subject. Otherwise, copy the following script into a file called ifDemo.m.
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.

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...