The purpose of this note is to give a basic introduction to writing MATLAB "scripts", which provides a basic means of writing programs. Upon completing the tutorial, you should know how to
A number of examples will be given below. No output is given in the tutorial since it is expected that you implement the examples yourself and then run them in the MATLAB command window to get the output.
Disclaimer: Many of the examples and exercises given below may seem to be irrelevant. However, by understanding them you will have all the background to write programs to solve all the homework problems.
In case your code has errors, MATLAB will complain when you try to run the program in the command window. When this happens, MATLAB will indicate what error occurred. You should try to interpret the error message and make necessary changes to the script in the editor. The error that is reported by MATLAB is hyperlinked to the line in the file that caused the problem. Using the mouse you can thus jump right to the line in your program that has caused the error. After you have made the changes, make sure you save your file before trying to run the program again in the command window.
The best programming advice, which applies to even the most experienced programmers, is to never try to write all the code at once. Programming should be done in small steps with each step tested to ensure it works before proceeding to program the next step. Implementing a longer program should always start with an outline using pen and paper before one line of code is ever typed into the editor.
As discussed in the introductory tutorials, there is no need to declare variable types anywhere in your script. However, it may be necessary to initialize some variables before they are used, and it is good MATLAB programming practice to initialize vectors and matrices to their proper sizes at the beginning programs. Furthermore, to avoid simple bugs that can be very difficult to find, you may consider adding clear all and close all at the beginning of your script to erase any values that may have previously been stored in these variables.
To make MATLAB give an output, such as return the value of a variable, you type the name of the variable without any semi-colon (;) following the variable. In many cases, there is no need to see the value of a variable every single time MATLAB uses it. If MATLAB re-computes the value of a variable 1000 times, we probably don't want to see the result every single time. To suppress the output of a value, just add a semi-colon after the variable. Then MATLAB will perform the command, but will not show it on the screen.
As a first example, consider the following program that takes a temperature value in Kelvin and outputs that value in Fahrenheit and Celsius.
Example 1:
clear temp_kelvin = 233.15; temp_celsius = temp_kelvin-273.15 temp_farenheit = 9/5*temp_celsius + 32 |
Note that values of temp_celsius and temp_farenheit are displayed in the command window since no semicolon is placed after these lines.
The power of computers is that they can repeat seemlingly mundane operations over and over (without getting bored!). 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 in MATLAB is the for-loop. The syntax for a for-loop is:
for loop_variable = start_value : end_value commandsend |
This loop will initiate 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.
This example fills a vector with the first 20 Fibonacci numbers and then plots the results using a logarithmic scale for the dependent variable (y-axis).
Example 2:clear n = 20; x = zeros(n,1); x(1) = 1; x(2) = 1; for i=3:n x(i)= x(i-1) + x(i-2); end semilogy(1:n,x,'xb-'); xlabel('n'), ylabel('nth Fibonacci number'); |
In the following example we see a so-called nested for-loop to fill in entries of a table according to some arithmetic pattern. This is nothing else then a "loop within a loop". Note how we must "close" each for with an end. Make sure you understand how this example works!
Example 3: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 purpose of the variable mysum. This is a common way of performing summations when programming.
Example 4:
clear
N = 10; mysum = 0; for k=0:N mysum = mysum+1/factorial(k); end e_approximation = mysum e_exact = exp(1) |
Now let's use a nested sum to approximate the value of $\exp(x)$ for $0\leq x \leq 7$ using 10 terms in the Taylor series of $\exp(x)$. We also plot the approximation as a function of $x$. Here we will include comments in the code using the percent sign (%). Any text following (%) on the same line will not be interpreted by MATLAB. This allows one to add comments which helps others understand what your code is suppose to do. Commenting your code is essential when writing programs.
Example 5:
clear N = 10; for k=0:70 x(k+1)=0.1*k; % Indices of vectors must be NON-ZERO!end semilogy(x,e) title('Approximation of e^x for x between 0 and 7') xlabel('x') ylabel('e^x') |