Matlab Tutorial Precept By Niki Kittur
Matlab is an extremely powerful tool that is fairly simple to use. This tutorial will give a broad overview of Matlab and will help to familiarize you with many of Matlab's useful features.
In Matlab, type "help" for a list of topics to get help on. Then type "help topic" for more detailed information. You can also use the command "lookfor keyword" if you know what you are searching for. Typing "why" will give you an insight into life, the universe and everything.
Matlab can be used for any operations you could do on a calculator. For example, if you type in ``4 * 3 + 2 * 5'' you should get back the answer 22. You can use variables instead of the actual numbers to do arithmetic, which have the advantage of not being erased after being typed once. So, if you type ``apples=4'' and ``oranges=2'', typing in ``cost=apples*3 + oranges*2'' will again give you the answer 22 and will store that answer in a variable called "cost". Matlab can also be used to find functions such as sin(x), sqrt(x) and log(x).
One of Matlab's strengths is its integral use of matrices. Arrays are simple one-row or one-column matrices which will demonstrate some of the basic matrix manipulations possible.
The simplest way to create an array is to simply define all its values. Assume we wanted to evaluate the function sin(x) from 0 to pi. Since there are infinite points in this range, we must choose a finite number of them; say we want to choose points at every 0.1*pi. Then we could make an array by typing ``x=[0.1*pi .2*pi .3*pi .4*pi .5*pi .6*pi .7*pi .8*pi .9*pi pi]'' Then to find the sin of these values we can simply type ``y=sin(x)'', which evaluates each point in the array x and creates a new array y of the same size in which it stores the output.
We can access this array in many different ways. If we simply wanted
to access one element, we could type ``x(3)'' for the third element in x.
To access a block of elements we can use colon notation: ``x(1:5)'' selects
the first through fifth elements in x. Similarly, ``y(4: -1: 2)'' means
to select elements 4, 3, and 2 in reverse order -- the format being
Using colon notation it is much simpler to construct arrays. Instead of typing out every point and value of pi in the above array we could type ``x=(0:0.1:1)*pi'', which constructs the equivalent array given the start, end and increment values. Alternately, we could type ``x=linspace(0, pi, 11)'', which tells Matlab the start and end points, and the number of data points in between.
Now we turn to manipulating the data in an array. As we have already seen by y=sin(x), it is simple to do mathematical operations between scalars and arrays. The scalars apply to each element of the array; thus, ``x-3'' subtracts 3 from each element in x. Array-array operations are only slightly more complicated. When the two arrays are the same size, addition, subtraction, multiplication and division can be applied on an element-by-element basis. However, when doing element-by-element multiplication or division the operator must be preceded by a . (.* or ./), otherwise the matrix multiplication or division operation is done. Another manipulation we can do with an array (and any matrix in general) is to change its orientation from rows to columns or vice versa using the transpose operation ('). Thus typing `` z=x' '' would create a column vector with the same values as the row vector x.
For more information on matrices type "help elmat" or "help specmat" at the Matlab console.
It is extremely simple to plot in Matlab, since it can can automatically choose limits for the axes, mark individual points and draw straight lines between them. You can also optionally plot multiple sets of data on the same graph, use different line types, mark only the data points, or use different colors for the curves.
If we want to plot sine wave array that we constructed earlier, all we would have to do is type "plot(x,y)". where x is the array of increments of pi and y=sin(x) (also an array). We can plot both sine and cosine on the same graph; to do this we first need to make an array to hold the cosine values by typing "z=cos(x)". Then we will plot both sets of data with "plot(x,y,x,z,'+')". The optional '+' tells Matlab to mark the data points of x,z using a plus so we can distinguish the two curves. We can also easily label the graphs, using the commands "xlabel('independent variable')" and "ylabel('dependent variables')", and title our graph with "title('your title here')". It is just as simple to create a 3D graph, using the command "plot3(y,z,x), grid". The optional ",grid" command simply a grid at the tick marks on the graph.
Matlab uses external files (called M-files because they end in a .m) to execute user-defined scripts and functions. To write a script M-file, simply place all the commands you would normally type at the console in a text file with a name ending in .m.
Matlab uses M-files for user-created functions. These functions can be quite useful as they can be called any number of times with different arguments, and can be passed to other functions which require functions as inputs (numerical analysis of ordinary differential equations, for example, requires the input of a function which provides derivatives).
The format of an M-file is:
function output variable = function_name(input var1, input var2...)
% Anything that appears here shows up when
% you type 'help function_name'
% Followed below by whatever the function does.
var1 = var2 + var3;
output variable = var1 * 2
If there is more than one output variable for a function, the output variables
are enclosed in brackets and separated by commas, so for example "[a,b]"
could be two output variables a and b for the function.
Matlab will search for the M-file automatically if its name is not the same as a built-in function. Thus the M-file should either be in the current directory Matlab is in or in one of the directories in Matlab's search path (type "path" to see a list of the search path directories). Some other useful commands when dealing with M-files are:
"what" -- lists all M-files in current directory
"ls" or "dir" -- list all files in current directory
"type mfile_name" -- shows the text of M-file mfile_name.m
"cd directory" -- changes to a directory
Matlab supports the use of control operators such as if, for, and while. The format for each of these is as follows. For a "for" loop, the syntax is
for n = array
commands
end
Thus an example would start "for x=1:5", and each time the "end"
is encountered x is assigned to the next column in the array. Note that
you can't reassign the loop variable n when you are within the loop to the
last column value so as to terminate the loop.
A "while" loop is a similar format:
while expression
commands
end
An example of would start "while (1+z(1))>1".
Not surprisingly, "if" conditionals are also similar:
if expression1
commands if expression1 is true
elseif expression2
commands if expression2 is false
.
.
.
else
commands if no expressions are true
end
Note that the "elseif" and "else" lines are optional.
Matlab can do a number of useful numerical analysis functions. Among those possible to do are minimization, zero finding, and solving differential equations.
The function "fmin" finds maxima and minima of a given function. The format of the function is: xmin=fmin(function_name,start_range,end_range) for finding the minima of a function. This command returns the minima of the function "function_name" and stores it in the variable xmin. Fmin can also be used to find maxima of functions by taking -f(x) instead of f(x) (the minima at f(x) will be the maxima at -f(x)).
The zero-finding function is almost identical to the minimization function. It's format is: xzero=fzero(function_name,start_range,end_range). This function returns the zero-crossing for a one-dimensional function.
Another extremely useful yet simple feature of Matlab is its ability to solve differential equations. The functions ode23() and ode45() use the second/third and fourth/fifth order Runge-Kutta methods respectively to solve an ordinary differential equation. The format of these functions are:
[t,y]=ode23('function_name',start,end,[init_val1; initval2;...]);
In the above, y is a column vector which will contain all of the variables, t is the time, function_name is the name of the mfile which contains equations for finding the derivatives of the variables, start and end refer to the time values to run the function over, and init_val1, etc. are the initial values of the variables contained in y. Thus you must first create an mfile which returns the derivative for each value as a column vector called yprime. The mfile would thus look like:
function yprime=function_name(t,y); initial values of any constants necessary yprime=[deriv of variable a deriv of variable b . . . deriv of variable z];
Each variable (a,b...,z) corresponds to a row in yprime, so 'a' would correspond to y(1), 'b' to y(2), etc. Using this method it is extremely easy to solve the differential equations in Assignment 3 (chemical chaos) with Matlab. Using what you have learned in this precept, use Matlab to solve and plot the differential equations in Assignment 3. Do your results match up with what you found when writing the program in C using the Runge-Kutta method?
[HL95] The Student Edition of Matlab
D. Hanselman and B. Littlefield
Prentice Hall, Englewood Cliffs N.J. (1995).