Sunteți pe pagina 1din 19

Appendix: Introduction to Matlab

1. Introduction
One of today's most widely used development and analysis packages is MATLAB, which is an acronym for matrix laboratory. Matlab was originally written to provide easy access to matrix software developed by the LINP ACK and EISP ACK projects, which together represent the state-of-the-art in software for matrix computation (reference to manual). Matlab provides its users with an easy to use environment for many tasks, such as: Mathematics and computations Algorithmic development and analysis Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including graphical user interface (GUI) building

For this reason, Matlab has become the package of choice for most of industry. There are, however, several other fine development and analysis packages. One such package is Mathematica, developed by Wolfram Research. Many people will argue over which of these two packages (Matlab or Mathematica) is better. Despite the claims from both sides, there's really not much you can do with one that you cannot do with the other. Each has an extensive set of built-in functionality. Also, there are many extensions to these programs that provide specific tools for a given area (e.g., signal processing, controls, and wavelet analysis). The difference between the two lies in the particular application at hand. If you are doing matrix computation, then Matlab is certainly the way to go. If you were doing any kind of analytical work, Mathematica is the obvious choice. However, it is Matlab's ease of programmability that has made it the choice for so many, and it is for this reason that I have chosen it as the package for which to base this paper on. 1.1 Command Prompt Basics The basic element of the Matlab programming language is the array. The array can be of many types. In the next section, we'll show how to use type double (precision) arrays. Later, we shall introduce a few other very powerful data types. In Matlab, an array of type double is any array composed of numeric data, that is, all numbers are stored with double precision. A great way to get started with Matlab is by typing "demo" at the command prompt. If you want to see if Matlab has a particular function, type "helpwin" at the command prompt. This brings up a figure window that will allow you to explore a complete listing of available Matlab functions (including toolboxes). This listing will provide a brief description next to the function name. You can find out more about the function (such as, what it requires for inputs) by typing "help function-name" at the Matlab prompt. For example,

help sin SIN Sine. SIN(X) is the sine of the elements of X. Overloaded methods help sym/sin.m These are good starting points, but the best way to learn Matlab is by working your way also attempt to point you in the right direction when necessary. 1.1.1 Defining Numeric Arrays a = [ 2 3 4 ] %this is a row vector a = 2 3 4 a = a' % this transposes a into a column vector a = 2 3 4 a = [2; 3; 4] % when placed in arrays [---], the ';' means start a new row a = 2 3 4 x = 0:1:4 % the colon operator is very useful. Here it means x = start: increment: end x=0 1 2 3 4 % Another example of using : x = 3:-0.5:-3 x= Columns 1 through 7 3.0000 2.5000 2.0000 1.5000 1.0000 0.5000 0 Columns 8 through 13 -0.5000 -1.0000 -1.5000 -2.0000 -2.5000 -3.0000

1.1.2 Accessing Elements of Arrays x = [ 3 2 1 4 ]; x(1) ans = 3 Notice: unlike the C programming language, the first element of an array is indexed by 1, not 0. x(1:3) ans = 3 2 1 % here we used the fact that numl : num2 has a default increment of 1. x(5) % this will produce an error since x does not have a 5th element ??? Index exceeds matrix dimensions. 1.1.3 Assignment x = 2; y = 3; z = x*y % note: ';' suppresses the x and y values z = 6 x(3) = 1 % places zeros where the function was not defined x = 2 O 1

clear all; % c1ears all variables in memory x ??? Undefined function or variab1e 'x'. % x is no longer defined x(3) = 1 % now the first element is also zero x= 0 0 1

1.1.4 Using Built In Functions Here is a basic list of built-in Matlab functions. To determine how they are used, type "help function-name" at the Matlab prompt (as was shown above for sin).

sin, cos, tan, sec, csc, cot, asin, acos, atan, asec, acsc, acot sinh, cosh, tanh, sech, csch, coth, asinh, acosh, atanh, asech, acsch, acoth log, log2, log10, exp, sqrt, pow max, mean, min, median, std, var, sum imag, real, i, j, abs, angle, cart2pol fft, ifft, interpn, spline, diff, del2, gradient and, or, xor, not, any, all, isempty, is* poly, roots, residue, polyfit, polyval, conv feval, fminbnd, fzero, quad, ode23, ode45, vectorize, inline, fplot, explot zeros, ones, det, trace, norm, eig

Elementary trigonometric functions and their inverses Elementary hyperbolic functions and their inverses Basic logarithmic and exponentiation functions Basic Statistical functions Basic complex number functions Basic data analysis functions Basic logical functions Basic polynomial operations Function functions. Allows users to manipulate mathematical expressions, and not just numeric arrays Basic matrix functions

The rest of this section will illustrate the use of some of the above functions. x = 0:0.01:pi; y = sin(x); max_val = max(y) max_val = 1.0000 min_val = min(y) min_val = 0

plot(x,y) ; % this is an example of using plot.m title('sin(x)'); xlabel('x'); ylabel('Amplitude') ;

To learn how to use the plot command, type "help plot" or "doc plot" at the Matlab prompt. We now will demonstrate some important uses of function functions (that is, Matlab functions that operate on mathematical functions). Before using function functions, always begin by expressing your mathematical function as a string (more about these later). For example, f = '2 + cos(x) '; f = inline(f) ; % redefine f to be an inline object fplot(f,[0 2*pi]) The next page contains the output from the execution of fplot. To see how to use any of above commands, you can of course use help or doc.

Here are some more examples of how to use function functions. x = fzero(inline('cos(x) ','x') ,1) % find a zero to cos(x) and start looking around x = 1 Zero found in the interval: [0.36, 1.64]. x = 1.5708 area = quad(vectorize(inline('x^2 + sin(x)', 'x')),0,pi) area = 12.3356 Computed the area of x2 + sin(x) over the interval [0 ].

2. Graphics
Matlab provides a very powerful set of graphic tools. Matlab graphics can be as simple as producing a plot of sin(x), or as sophisticated as building graphical user interfaces. We only intend to demonstrate some of the basic commands, for details on Matlab graphics see (9). Here is a basic list of basic plotting commands:

plot, plot3, mesh, cplxgrid, meshgrid, surf, stem subplot, title, x label, label, legend, axis, text, gtext et, get, gca, findobj, gcf

Basic functions that allow the plotting of functions of one or more variables Basic functions for modifying the appearance of plots Basic Handle Graphics commands

The rest of this section will illustrate the use of some of the above functions. clear all; x = -1:0.01:1; f1 = x.^2 + x.^3; % note the dot in front of ^ plot(x,fl,'r-.') ,xlabel('x') ,ylabel('f'),title('x^2 + x^3');

Note how multiple commands can be executed at the prompt by separating them with a comma. Though it cannot be seen in this text, the line is red and has a "dash-dot" structure. The default color in Matlab is blue with the line being solid.

f2 = cos(x);f3 = sin(x); f4 = f2 + f3; plot(x,f2, 'b-. ' ,x,f3, 'g-+' ,x,f4, 'r-* ) , x label ( x' ) , ylabel ( y ) , titIe ( Trig Functions'),legend('cos', 'sin', 'sin + cos', 0);

3. Matrix Computations
3.1 Basic Calculations This section shall illustrate some of the basic operations of matrix algebra, and some specialized functions used extensively in Matlab. For a more detailed introduction see (7). For material on matrix computations see (3). clear all; a = [ 3 4 5; 6 7 8; 9 10 11]; b = [-3,-4,-5; -6,-7,-8; -9,-10,-11];

a+b ans = 0 0 0 2*a ans = 6 12 18 a b ans = 6 12 18 8 14 20 10 16 22 8 14 20 10 16 22 0 0 0 0 0 0

a*b % ordinary matrix multiplication ans = -78 -90 -102 -132 -153 -174 -186 -216 246 Here we illustrate a very important type of matrix product: element-by-element matrix multiplication, also referred to as a Hadamard product. (3:4) a.*b% use the .* operator ans = -9 -36 -81 -16 -25 -49 -64 -100 -121

a.^2 % another use of the .operator ans = 9 36 81 16 49 100 25 64 121

sin (a) % element by element sin-[sin(3) sin(4) etc...] ans = 0.1411 -0.2794 0.4121 -0.7568 0.6570 -0.5440 -0.9589 0.9894 -1.0000

3.2 Factorization and Linear Systems This section will illustrate some basic factorizations of matrices. clear all; x = rand(4) % and 4 by 4 matrix of random numbers taken from a uniform distribution x = 0.9501 0.2311 0.6068 0.4860 0.8913 0.7621 0.4565 0.0185 0.8214 0.4447 0.6154 0.7919 0.9218 0.7382 0.1763 0.4057

[S U V] = svd(x) % the singular value decomposition S = 0.7301 0.4413 0.3809 0.3564 U = 2.4479 0 0 0 V = 0.4903 0.4770 0.5362 0.4945 -0.4004 0.6433 -0.5417 0.3638 0.5191 0.4642 -0.2770 -0.6620 -0.5743 0.3783 0.5850 -0.4299 0 0.6716 0 0 0 0 0.3646 0 0 0 0 0.1927 0.1242 0.6334 -0.3254 -0.6910 0.1899 -0.3788 0.6577 -0.6229 -0.6445 0.5104 0.5626 0.0871

[Q R] = qr(x) % produces a qr factorization Q = -0.7606 -0.1850 -0.4858 -0.1354 -0.8151 0.0754 0.4523 -0.5489 0.0617 0.4457 -0.0062 -0.8686

-0.3890 R = -1.2492 0 0 0

0.5582

-0.7002

0.2163

-1.0478 -0.6971 0 0

-1.3141 0.0148 -0.3892 0

-1.0811 -0.4867 -0.2615 0.3409

[L U] = lu(x) % produces an LU decomposition of x L = 1.0000 0.2433 0.6387 0.5115 U = 0.9501 0 0 0 0.8913 0.5453 0 0 0.8214 0.2449 0.5682 0 0.9218 0.5140 0.3465 -0.3924 0 1.0000 -0.2069 -0.8021 0 0 0.2490 1.0000 0 0 1.0000 0

This part will illustrate the solution of Ax = b type problems. A = [8.8, 9.1,-4; 7.0, 1.2, 0.897; 3.2, -8.3,10.0]; b = [2; 3; 4] ; x = inv(A)*b x = 0.4305 -0.1279 0.1560 Or we can use the \ operator: x = A\b x= . 0.4305 -0.1279 0.1560

At anytime during your Matlab session, you can see what variables you have in memory by typing "whos" at the command prompt. whos Name A L Q R S U V b p x Size 3x3 4x4 4x4 4x4 4x4 4x4 4x4 3xl 4x1 3xl Bytes 72 128 128 128 128 128 128 24 32 24 Class double double double double double double double double double double array array array array array array array array array array

Grand total is 115 elements using 920 bytes clear; % same as clear all. Deletes all variables from memory whos % no output because there are no variables in memory A few other useful commands while working at the Matlab command prompt are clc, who, and close. Being able to perform all the above computations at the command prompt is useful, but the real power of Matlab is its programmability. In the next section, I'll outline the basic elements of writing your own programs in Matlab.

4. Basics of Programming In Matlab


4.1 Where and How to Start Writing Your Own Programs As with any other programming language, when one wishes to write an actual program, they must begin with some form of editor. Matlab has a built-in editor that allows for the debugging and writing of Matlab code. Typing "edit" at the Matlab prompt will cause the editor/debugger to open. The editor looks just like your typical text editor. This section will not illustrate the use of the debugger. For an introduction on how to use the Matlab debugger and editor see (7). There are two main types of programs you can write: scripts (also called m-files because of their .m extension) and functions. Scripts are programs that, when executed, will have each of its commands executed of if they were entered at the command prompt. Scripts can use variables that are currently in the workspace; also, when executed, variables defined in a script shall be accessible from the workspace. Functions are programs that, when executed, return a set of specified outputs obtained from a given set of inputs. Functions can only "see" variables that are passed to it as inputs, and will only return (to the workspace) variables that are specified as outputs. The best way to understand the difference is by a couple of examples.

Suppose the following was typed in the Matlab editor and the saved as example1.m: %examplel.m x=4; y= 5; z = x + y; t = 0:0.1 :pi; plot(t,sin(t)); At the command prompt, we can run the script example l by simply typing its name. clear; % clear all variable example1

whos Name T X Y Z Size 1x32 1x1 1x1 1x1 Bytes 256 8 8 8 Class double double double double array array array array

Grand total is 35 elements using 280 bytes z z = 9 x x = 4 y y = 5 The results of script file were all sent to workspace. The use of a function shall now be illustrated. Suppose the following was typed in the Matlab editor and the saved as example2.m: function [ out_arg1 ,out_arg2] = example2(in_arg1 ,in_arg2) % this function returns the sum and difference of the two inputs out_argl = in_argl + in_arg2; out_arg2 = in_argl in_arg2; At command prompt we will now execute the function example2.m: clear; [x,y] = example2([4 3] , [9 3]) x = 13 y = -5 0 6

There are a couple of important things to notice here: one, the program does not make any distinction as to the size of the inputs. That is, the fact that we used two row vectors instead of just two numbers as inputs made no difference to Matlab. This an extremely important point to remember when writing your own programs. Matlab is an array-based language; if you program it as you would in C or Fortran, you're really doing yourself a disfavor. The second point to notice is that when we called the function example2.m, we called our outputs x and y instead of out_argl and out_arg2. In Matlab, the names of output arguments are just placeholders. They do not have a definite name until you specify one. Also, you do not always have to specify all the arguments. For example, z = example2(3,4) z = 7 Here it returns the sum of the two inputs, but not the difference. The reason is, we only specified the first of the outputs. Thus, only the first one was returned. 4.2 Flow Control " Matlab has several flow control constructs: if statements switch statements for loops while loops break statements return statements

The if structure: clear all; x = 2; y = 3; if x > y z = x + y; elseif x < y z = x -y; else z = x; end z z = -1

The switch structure: n = 5; switch ( rem(n,2) ) case 0, disp('n is an even number or zero'); case 1, disp('n is an odd number'); otherwise, disp('n is not a positive integer'); end n is an odd number The for loop: clear; x = []; tot = 0; for ii = 1:5 x = [x ii]; tot = tot + ii; end x x = 1 tot tot = 15 2 3 4 5

The while loop: clear; n = 0; while n < 10 x = n^2; n = n + 1; end n n = 10 x x = 81 Notes on the break and return commands: The break command allows for the early exit of a while or for loop. The return command stops the execution of a function and returns control back to the command prompt, or the "main function." That is, the function that was calling the function that was terminated early due to a return statement.

5. Other Data Structures


5.1 Structures and Cell Arrays As problems get more complicated it is very important to use appropriate data structures. The choice of a good data structure can simplify one's "algorithmic life." (6:59) If you are a C programmer, then you probably already have a good idea of what a structure in Matlab is. A structure is a Matlab array that divides its contents up into fields. The fields of a structure can contain data types different from one another, and this is the main reason for their use. A few examples will illustrate how they are defined and used. S.name = 'Jason Knapp'; S.age = 22; S.egr_335_grade = 'A'; S.grade = 'senior'; Here, our structure is S, and the fields are name, age, egr_335_grade, and grade. Now that we have defined a structure, we need to know how to access the information contained within its fields.

S.name ans = Jason Knapp z = S.age*2 z = 44 To reiterate: structures can contain data of any type, arrays, strings, other structures, and cell arrays. A useful function when using structures in Matlab is the struct command. Now on to cell arrays. Cell arrays are Matlab arrays that can contain data of any type, but unlike structures that store their data in fields, cell arrays store their data as actual elements. An example will illustrate their use. clear; a{1, 1} = ones(3,1); a{2, 1} = 'This is second row and first columns'; a{2, 2} = randn(3) ; a{1, 2} = 'row 2 column 2 is a 3x3 random matrix'; With cell arrays, when assigning elements use the curly brackets instead of parentheses. Here is how to access the elements of a cell array: a{l,l} ans = 1 1 1 sub cell = a (1: 2,2) % this is a cell array, note the use of( ) instead of { } sub cell = 'row 2 column 2 is a 3x3 random matrix' [3x3 double]

X = 3*a{2,2} X = 0.5239 -0.5601 2.1774 a{1,2} ans = row 2 column 2 is a 3x3 random matrix clear all; -1.7649 6.5496 -0.4092 0.3418 3.2003 0.1778

6. End Notes
Matlab is a very powerful tool. It is excellent for algorithmic development and system prototyping. To learn more about what Matlab has to offer, visit www.mathworks.com

S-ar putea să vă placă și