Introduction To Matlab 1
Introduction To Matlab 1
Goal
The goal with this worksheet is to give a brief introduction to the mathematical software Matlab. After completing the worksheet you should know how to start Matlab, how to use the elementary functions in Matlab and how to use Matlab to plot functions.
What is Matlab?
Matlab is widely used in all areas of applied mathematics in education and research at universities and in the industry. Matlab stands for MATrix LABoratory and the software is built up around vectors and matrices. This makes the software particularly useful for linear algebra which we will see later in the course but Matlab is also a great tool for solving algebraic and differential equations and for numerical integration. Matlab has powerful graphic tools and can produce nice pictures in both 2D and 3D. It is also a programming language (similar to C) and is one of the easiest programming languages for writing mathematical programs. Matlab also has some tool boxes useful for signal processing, image processing, etc.
encouraged to use. The writing area that you will see when you start Matlab, is called the command window. In this window you give the commands to Matlab. For example, when you want to run a program you have written for Matlab you start the program in the command window by typing its name at the prompt. The command window is also useful if you just want to use Matlab as a scientific calculator or as a graphing tool. If you write longer programs, you will find it more convenient to write the program code in a separate window, and then run it in the command window (this will be discussed in Introduction to programming in Matlab 1). In the command window you will see a prompt, on Macs and PCs this prompt is >> . You type your commands immediately after this prompt. Once you have typed the command you wish Matlab to perform, press <enter>. If you want to interupt a command that Matlab is running, type <ctrl> + <c>.
at the prompt. Be careful with parantheses and don't forget to type * whenever you multiply! Note that Matlab is case sensitive. This means that Matlab knows a difference between letters written as lower and upper case letters. For example, Matlab will understand sin(2) but will not understand Sin(2). Here is a table of useful operations, functions and constants in Matlab. Operation, function or constant + (addition) - (subtraction)
X (multiplication)
Matlab command
+ * / abs(x) sqrt(x) exp(x) log(x) log10(x) sin(x) cos(x) tan(x)
/ (division) | x | (absolute value of x) square root of x ex ln x (natural logaritm of x) log10 x (base 10 logaritm of x) sin x cos x tan x
Exercises
Compute the following expressions using Matlab:
3cos(pi) 1+1+1/2+1/6+1/24-e ln (1000+2pi-2) e i pi The number of combinations in which 12 persons can stand in line. (Hint: Use factorials.)
Variables in Matlab
We can easily define our own variables in Matlab. Let's say we need to use the value of 3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote this variable as x by typing the following:
x=3.5*sin(2.9)
and observe what happens. If we do not want to see the result of a calculation we can use semicolon to surpress the print-out on the screen even though Matlab still performs the command in "the background". If you defined x as above, now type
y=2*x; y
and observe what happened. In many cases we want to know what variables we have declared. We can do this by typing whos. If you want to erase the variable from the Matlab memory, type clear.
Matrices can be created according to the following example. The matrix A= created by typing
A=[1 2 3 ; 4 5 6 ; 7 8 9 ],
is
i.e., rows are separated with semi-colons. If we want to use a specific element in a vector or a matrix, study the following example: Example:
x=[10 20 30] A=[ 1 2 3 ; 4 5 6 ; 7 8 9] x(2) A(3,1)
Here we could reach the second element of the vector by typing the variable and the position within parantheses. The same principle holds for matrices; the first number specifies the row of the matrix, and the second number specifies the column of the matrix. If the matrices (or vectors which are special cases of a matrices) are of the same dimensions then matrix addition, matrix subtraction and scalar multiplication works just like we are used to. Example: Type
x=[ 1 2 3]
and observe what happens. If want to apply an operation such as squaring each element in a matrix we have do use a dot . before the operation we wish to apply. Type the following commands in Matlab.
x=1:10 x.^2 A=[1 2 3 ; 4 5 6 ; 7 8 9 ] A.^2 A^2
and observe the result. Note the dot and what it accomplishes! All built-in functions such as sin, cos, exp and so on automatically act elementwise on a matrix. Type
y=[0 1/4 1/2 3/4 1] y=pi*y sin(y)
plot(x,y)
and observe what happens. The following commands are useful when plotting: Graphing functions Label the horizontal axis. Label the vertical axis. Attach a title to the plot. "Keep plotting in the same window." Turn off the "keep-plotting-in-the-samewindow-command". Matlab command
xlabel('text') ylabel('text') title('text') hold on hold off
Note that all text must be put within ' '. The last two commands (hold on and hold off) are best explained by trying them next time you plot.
Exercises
Plot sin(x) on the interval [-pi,pi] using spacing 0.5, 0.1 and 0.01 between the points where you will sample the function. (This will change the resolution). Experiment with the hold on command. Attach labels to the axis of the previous plot and give a title to the graph. Plot 5 cos(x2+1) on [-2pi,2pi]. Note that the squaring operation will require you to use the dot . in order for the squaring operation to act on each element individually. However, the addition operation (+) automatically acts on elements individually.
norm(A,inf) norm(A,'fro')
The command eig(A) returns only the eigenvalues or both eigenvalues and a set of eigenvectors depending on how you use the command. This is illustrated in the example below. Example 1.
A = [ 1 2 ; 2 1 ] e = eig(A) [X D] = eig(A); X D B = [1 i ; 2 3] B' B.'
The example above illustrates two ways of using the command eig. The first time it is used, it simply returns all eigenvalues in a vector. The second time eig is used, it returns a set of eigenvectors as columns in the matrix X and the eigenvalues as diagonal elements in the matrix D. Exercise 1. Verify that the columns of X in the example above indeed are eigenvectors to the matrix A. In other words, multiply (using Matlab) the matrix A to the columns (one at a time) of X and check that they are eigenvectors corresponding to the eigenvalues. Matlab has a very powerful method for solving system of equations. The syntax is simple. The following example solves the systems Ax=y using a very reliable algoritm. Example 2.
x = A\y
Example 3.
A=[ 1 2 ; 3 1 ] [L U]=lu(A) [Q R]=qr(A) B= [ 1 2 ; 3 4 ; 5 6] [U S V]=svd(B)
Exercises
Exercise 2. Define the matrices
A=[ B=[ C=[ y=[ 17 2 3 4 ; 5 6 7 8 ; 9 10 11 12 ; 13 14 15 16 ] 2 3 4 5 ; 6 7 8 9 ; 10 11 12 13 ; 14 15 16 17 ] 1 2 3 ; 4 5 6 ; 7 8 9 ] 4 3 2 1 ]' Note the transpose ' on the y-vector which makes y a column vector.
a) Compute AB and BA. Is matrix multiplication commutative? b) Compute AC. Why do you get an error message? c) Solve the following system of equations: 17x1+2x2+3x3+4x4 = 4 5x1+6x2+7x3+8x4 = 3 9x1+10x2+11x3+12x4 = 2 13x1+14x2+15x3+16x4 = 1 Once you have found the solution x verify that it indeed solves the system. (This is easy once you have formulated the system as a matrix equation.) Exercise 3. Find the eigenvalues and a set of eigenvectors to the matrix A defined above. Exercise 4. a) Solve x''+x'+x=0 by hand (using the characteristic polynomial). b) Next re-write this ODE as a system of first order equations. Find the eigenvalues of the assoicated matrix. c) What is the relationship between the roots of the characteristic polynomial you found in a) and the eigenvalues? (This relationship is not a coincidence! It will be true for all linear ODEs.) Exercise 5. Using the observation in Exercise 4c) above, solve x'''+6x''+11x'+6x = 0 by writing it as a system of equations and then finding the eigenvalues (using Matlab). Exercise 7. Find the singular values of the matrix A=[ 1 3 ; 2 5 ; 6 7 ]. Check that the matrices U and V that Matlab returns according to Example 3 indeed are unitary matrices.
This worksheet introduces the fundamental ideas for programming in Matlab. It requires no programming experience, but some familiarity with Matlab is recomended. All background needed can be found on the worksheet Introduction to Matlab. The programming structures presented below applies to Matlab. However, these structures look very similar in other computer languages, such as C, Java, Pascal, etc., so by understanding how loops, logical operations, etc., work in Matlab, you will be well-prepared for beginning programming in other languages as well. Many of the examples given may seem to be irrelevant to this course. However, by understanding the seemingly stupid and sometimes mathematically irrelevant examples and exercises in this worksheet, you will have all the background to write programs such as a RungeKutta 4 ODE-solver. A number of examples will be given below. They will be given as Matlab code but the output which you will get when you run these programs will not be given. When going over this worksheet, you are recomended to implement the examples yourself and then run them in the Matlab command window and carefully study the outcome and compare it to the code.
In case your code has errors, Matlab will complain when you try to run the program in the command window. When this happens, try to interpret the error message and make necessary changes to you code in the editor. After you have made the changes, make sure you save your file before trying to run the program again in the command window.
Let's say that we want the user to enter some value that we want the program to work with. This can be done using the input command with the syntax variable=input('text'); This command will print out text on the screen and then wait for the user to enter a number. The variable will now be assigned the number that the user entered. (Using this command for reading letters instead of numbers is slightly more complicated and will not be covered in this worksheet.) Now it is time for our first example. The following program asks the user for an amount in dollars, and returns the value of this amount in a foreign currency. Example 1.
clear exchange_rate = 0.5; amount = input('Give amount in dollars: ');
amount_in_foreign_currency = exchange_rate*amount
Always begin your code with clear! This erases all variables. If you do not do this, you can get errors when you run your program that are very hard to discover.
Relational and logical operators The heading may sound scary but are just fancy names for some of the fundamental operators used for programming. Below follows a list with some useful commands.
Logical operators
Operation: Matlab command: Logical and & Logical or | Negate
~
Relational operators
Operation: Strictly less than Less than or equal to Strictly greater than Matlab command:
< <= >
It is important to know the difference between = and ==. The former, =, is used when assigning a number to a variable, e.g., x=3;. The latter, ==, is used to check if two expressions are equal. This is illustrated in the examples below, but first we need to know what an if-statement is. When programming we often want the computer to check whether a statement is true or false and
perform different operations depending on the result of this test. This can be done using a socalled if-statement. The syntax is given below.
if logical expression
commands
else
commands
end
Note that for each if, you need to "close" the if-statement with an end. Make sure the if:s and end:s always match! (This is a common source for programming errors.) The content of this paragraph may have seemed abstract but by carefully studying the following three examples and doing Exercise 1 it will hopefully become clearer. Example 2.
clear N = input('Give numerator: '); D = input('Give denominator: '); if D==0 'Sorry, cannot divide by zero' else ratio = N/D end
In the next example, I make Matlab write something depending on which test our month "passes". To make Matlab write text as output, use single quote ' around the text. Example 3.
if month==1 | month==3 | month ==5 | month==7 | month==10 | month==12 'Your month has 31 days' else if month==2 'Your month has 28 days' else 'Your month has 30 days' end end
In the next example I use the command rem (remainder). The syntax is
rem(x,y)
and returns the remainder after the division of the two integers x and y. Example 4.
clear number = input('Give an integer: ' ); remainder2 = rem(number,2); remainder3 = rem(number,3); if remainder2==0 & remainder3==0 'Your number is divisible by both 2 and 3' else if remainder2==0 'Your number is divisble by 2 but not by 3' else if remainder3==0 'Your number is divisible by 3 but not by 2' else
Exercise 1. Write a "currency exchange program" similar to the one in Example 1 which can handle two different exchange rates, exchange_rate1 = 0.5 and exchange_rate2 = 0.25. Design the program to first ask for the amount in dollars and then ask the user which rate (represented by the numbers 1 and 2 respectively) he/she wants. Let the program return the amount in the requested foreign currency.
Repetitive operations (loops) The power of computers is that they can do operations repeatedly. For example, an ODE-solvers computes the value of a function several thousands of times when choosing a small time step. An operation that is performed repeatedly is called a repetitive operation or, more common, a loop. There are different kinds of loops but the most common one is the for-loop. The syntax for a for-loop is:
commands
end
This loop will initate loop variable as start value, increment loop variable by 1 each step until end value is reached. Below follows a few examples of how to use for-loops. Example 5.
In the following example we see a so-called nested for-loop. This is nothing else then a "loop within a loop". Note how we must "close" each for with and end. Make sure you understand how this example works! Example 6.
In the following example, make sure you understand the function of the variable sum. This is a common way of performing summations when programming. Example 7.
clear sum = 0; for k=0:10 sum = sum+1/gamma(k+1); end e_approximation = sum e_exact = exp(1)
In the next example, notice how I have to "shift" the indexing of the vector. Matlab must have non-zero, positive integers as vector- or matrix-indices! One of the most common mistakes when programming in Matlab is that your program begins indexing at zero instead of one. Also note how by typing a percent sign (%) before text in the code, Matlab does not interpret this text as code. It just serves as a comment for any person using the code. Commenting your code is essential when writing longer programs. Example 8.
clear for k=0:50 x(k+1)=0.1*k; % Indices of vectors must be NON-ZERO! sum = 0; for m=0:10 sum = sum+(x(k+1)^m)/gamma(m+1); end e(k+1) = sum; end plot(x,e) title('Approximation of e^x for x between 0 and 5') xlabel('x') ylabel('e^x')
Exercise 2. Write a program that approximates PI by computing the sum . The more terms you keep in the summation, the more accurate your answer will be. (In fact, the series converges to PI as m goes to infinity.) See how many terms you need to approximate PI with 5 decimals. (Note: This is by no means the most efficient way to approximate PI, but the formula is quite beautiful...) Exercise 3. Use the sum given in Exercise 2 to approximate PI using 10,100, 1000,10,000 and 100,000 terms. For each of these number, compute the error of the approximation. Plot the error as a function of the number of terms used in the sum.
Functions in Matlab
You have already encountered functions that are built in to Matlab. The sin() is a function that takes an argument and returns an output. As you start to write your own programs in Matlab you will need to create your own functions that takes one or more arguments and does something with these arguments. For example, when you write an ODE-solver you will probably have a loop calling "the right-hand side" of your ODE (i.e., f(t,x) in x'=f(t,x)) thousands of time. You could type this function explicitly in your loop, but you probably want your ODE-solver to be able to handle more than one ODE and then it will convenient to write your right-hand side of the ODE as a function. Another example when you want to use functions in Matlab is if you want to make a graphing program. This will be illustrated in the example below, but let's first look at the syntax for a function in Matlab. function y=function name(argument list) commands The code above must be written in a separate m-file! The name of the file should coincide with the name of the function. Remember to save the file with a .m after the file name. The syntax above is illustrated by an example. The example defines a function in a function file named f.m and is saved in the same directory as the file functionplotter.m. Example 1.
% Filename: f.m function y = f(t) y = exp(-t)*sin(3*t);
You must type and save the file f.m before you can use the code in functionplotter.m. Once you have typed and saved both these files and saved them in the same directory, you run the program in the Matlab command window by typing functionplotter. This code will call the function file f.m each time it needs to compute the function you specified in the file f.m. Note that it is not necessary to have a clear command in the function file f.m. Make sure you understand how this example works. It will help you to write the ODE-solver later. Exercise 1. Make a plot of the function exp(t)*cos(5*t) for t between 0 and 10. (Hint: Do you need to change the file functionplotter.m at all?) It is possible for functions to have more than one argument which the following "stupid" example illustrates. Example 2.
% Filename: g.m (remember, file name must match % with the name of the function) function y = g(t,x1,x2) y = sin(t+x1+x2);
The example above shows how you can use functions of three variables.
Before you begin coding ask yourself (and write down your answer on a piece of paper) the following questions: 1. What is my input? What should I name these variables? What types are my inputs? (That is, are my inputs files, variables, vectors...?) 2. What is my output? (For example, is it a number, a plot or something else.) 3. What are my main procedures in my program? That is, what are the main steps my program needs to perform? (Don't answer in details and commands at this stage. Try to specify your answers to these questions in words.) One way of answering these questions, is in a form of diagram. The diagram for an Euler forward ODE solver may look something like shown in Diagram 1. Once the above questions are answered, we observe that the most tricky part might be the problem of iterating Eulers method to find a solution. Therefore we should try to specify this step. One way of specifying what we need to do in this step is to extend our first diagram by adding information of how to do the loop. This can be experessed symbolically as in Diagram 2. Now we have specified what our program has to do so now we are in position to start coding. In this case, I would recommend you to start with the function file. Once this one is written, start typing your main code, but make sure to check that each (small) step works, before you proceed to the next step of the code! Here is an example of the code for an ODE solver. In case you feel comfortable with programming you can already now start doing Exercise 2 below, rather than typing in the code of Example 2. The following example solves the equation x'(t)=-x which you can solve analytically. The reason for choosing such an easy function is that you know what the solution should look like and therfore you can check that your solver works as expected before you try more tricky equations. Below I will use the % frequently to add comments to the code. I will also use the command ceil( ) which take an argument and rounds it to the nearest greater integer. Please compare the code to Diagram 2. Example 3.
% Filename: f.m (name must match with the name of the function) function y = f(x) y = -x;
% Filename: ef.m clear t0 = 0; % Start time tfinal = 10; % Final time x0 = 1; % Initial value (x(t0)) h = 0.05; % Time step N = ceil( (tfinal-t0)/h ); % Computes the number of loop steps t(1) = t0; % t( ) will be a vector with the time grid
x(1) = x0; % x( ) will be a vector with the "solution" for each time value for k=1:N t(k+1) = h*k; % Fills the time grid vector x(k+1) = x(k)+h*f(x(k)); % Euler forward iteration end plot(t,x)
Exercise2. Write your own RK4 solver for autonomous first order ODEs. Test your solver on the following IVP: x'=x, x(0)=1. If it works, try it on some more tricky equation. The RK4 iteration scheme for autonomous first order ODEs is k1=f(x(k)) k2=f(x(k)+h*k1/2) k3=f(x(k)+h*k2/2) k4=f(x(k)+h*k3) x(k+1)=x(k)+h*(k1+2*k2+2*k3+k4)/6 If you find this exercise too difficult, you can work on the examples and exercises given in this and the other worksheets and maybe try to extend/improve them. Do not feel pressure to finish the RK4-solver but if you like programming this is a good exercise.