Matlab Programming
Matlab Programming
Page 1
by Kristian Sandberg Department of Applied Mathematics University of Colorado 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 Runge-Kutta 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.
Matlab Programming 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
Page 2
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 Equal to Not equal to 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 so-called 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
http://amath.colorado.edu/computing/Matlab/Tutorial/Programming.html
26-10-2012 14:45:20
Matlab Programming 'Sorry, cannot divide by zero' else ratio = N/D end
Page 3
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. clear month = input('Give month number (1-12): ' ); 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.
http://amath.colorado.edu/computing/Matlab/Tutorial/Programming.html
26-10-2012 14:45:20
Matlab Programming
Page 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 'Your number is not divisible by either 2 or 3' end end end
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:
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. clear for i=1:20 x(i)=i/7; end x
http://amath.colorado.edu/computing/Matlab/Tutorial/Programming.html
26-10-2012 14:45:20
Matlab Programming
Page 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. clear for i=1:5 for j=1:5 A(i,j)=10*i+j; end end A
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 matrixindices! 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')
http://amath.colorado.edu/computing/Matlab/Tutorial/Programming.html
26-10-2012 14:45:20
Matlab Programming Exercise 2. Write a program that approximates PI by computing the sum
Page 6
. 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, 10000 and 100000 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.
http://amath.colorado.edu/computing/Matlab/Tutorial/Programming.html
26-10-2012 14:45:20