matlab - Download as DOC by yPsYn3x

VIEWS: 0 PAGES: 17

									MATLAB: An Introduction



Adapted from an introductory manual by
           John Buck, MIT
             27 May 1989




              Edited by
       Yin-ping (Daniel) Chang
         22 September 2002
                                                                                                        Matlab Intro


3. MATLAB Commands

To do work in MATLAB, you type commands at the >> prompt. Often these commands will look like standard
arithmetic, or function calls similar to many other computer languages. By doing this, you can assign sequences to
variables and then manipulate them many ways. You can even write your own functions and programs using
MATLAB's control structures. The following sections will describe the most commonly used commands on
MATLAB and give simple examples using them.

To make life easier, MATLAB includes a simple line-editing facility. If you make an error while typing a command,
you don't have to retype the whole command. You can just call up the last line you typed and fix the error. To recall
the last line you typed, hit the up arrow. MATLAB actually saves several of your last commands, so you can
continue moving backwards through your prior commands by hitting the up arrow more than once. If you happen to
move too many commands backwards, you can hit the down arrow to move to the next command (i.e. the one you
just went past by hitting the up arrow). The left and right arrows move you left and right one character, respectively.
Similarly, Ctrl-L and Ctrl-R will move you left and right one word. Ctrl-B will move you to the beginning of the line,
and Ctrl-E will move you to the end of the line. Ctrl-A will toggle you between insert and overwrite mode for line-
editing. Finally, as you might well expect, backspace will delete the character to the left of the cursor.


3.1. Basic Terminology

MATLAB has some basic terms and predefined variables you should get familiar with before going any further. One
of these is the variable ans. When you type most commands to MATLAB, they will return values. You can assign
these values to variables by typing in equations. For example, if you type

>>x=5

MATLAB will print

x=
            5

and assign the number five to the variable x. MATLAB uses ans for any expression you don't assign to a variable.
For instance, if you type

>> 5

to MATLAB, MATLAB will return

ans =
             5

and assign the value 5 to the variable ans. Thus, ans will always be assigned to the most recently calculated value
you didn't assign to anything else.

MATLAB creates a variable called eps every time you run it. eps is the distance from 1.0 to the next largest floating
point number. Basically, it is the maximum resolution of the system for floating point arithmetic. On the 486 PC
workstations, eps = 2.2204e-016. MATLAB also keeps a permanent variable named pi, which is defined as 3.1415....
The permanent variable Inf represents the IEEE positive infinity. This should be returned by evaluating an
expression such as 1.0/0.0. Similarly, the permanent variable NaN represents a value which is not a number, such as
the result of evaluating 0.0/0.0.

As the earlier examples showed, whenever you type a command to MATLAB, MATLAB returns the value returned,
and the variable to which that value was assigned. Sometimes, you don't want to see this. For example, if you assign


                                                    Matlab-2
                                                                                                          Matlab Intro


b to be the integers from 1 to 1000, you probably don't want to wait for MATLAB to print them all out. If you
terminate a command with a semi-colon, MATLAB will suppress the printing of the variable name and value
resulting from the calculation. For example, if you type

>> x = 5;

MATLAB will assign the value five to the variable x, but rather than tell you it did that, it will just return another >>
prompt.

MATLAB works with two basic types of data objects: scalars and matrices. MATLAB also has vectors. Vectors are
a special case of matrices which are only 1 row by any number of columns. Vectors can be used to represent
discrete-time sequences. We showed earlier how to assign a scalar, such as five, to a variable. To assign x to be a
matrix by explicitly entering the elements, you type the list of elements separated by blanks or commas surrounded
by [ and ], and use semi-colons to separate the rows. For example, typing

>>x=[2468; 1 357]

results in

x=       2         4       6         8
         1        3        5         7

The MATLAB workspace is defined as the collection of all the variables you have defined during the current
MATLAB session. A session is defined as beginning when you type the command matlab to Athena, and ends when
you type the quit command to MATLAB. While MATLAB has room for a substantial amount of variables, it can
get very full if you are working with large vectors or matrices. Shortly, we will show you how to see what variables
are in your workspace, and how to save your workspace so you can continue your session later.

MATLAB can do complex arithmetic. However, it does not explicitly create a variable named i. You will need to do
this yourself if you want to enter complex numbers. You can do this by typing

>> i=sqrt(- 1)

MATLAB will return:

i=
         O + 1.000I

You can name this variable j if your tastes run that way. Now, you can use complex numbers of the form a + bi
simply by typing a + b*i. For example, to set y = 2 + 3i, you would type

>> y = 2+3*i

At times, you will want to deal with just a part of a vector or matrix. To do this, you need to use MATLAB's
indexing facility. To get the nth element of the vector x, you type x(n). MATLAB starts counting from one when
numbering vector elements, so the first element of x is x(l) and not x(O). C hackers should be especially careful
about this. You can also use indices on matrices. The element in the ith row, jth column of x is x(i,j).

3.2. Basic Arithmetic

MATLAB uses a straightforward notation for basic arithmetic on scalars. The symbol + is used to add scalars, so
x=1+5 will give x the value 6. Similarly, MATLAB uses - for subtraction, * for multiplication, / for division, and ^
for exponentiation. All of these work for two scalars. In addition, you can add, subtract, multiply or divide all the
elements of a vector or matrix by a scalar. For example, if x is a matrix or vector, then x+1 will add one to each

                                                     Matlab-3
                                                                                                        Matlab Intro


element of x, and x/2 will divide each element of x by 2. x^2 will not square each element of x. We'll show you how
to do that later. All of the basic operations (+, -, *, /, and ^) are defined to work with complex scalars.

Another useful operator is the colon. You can use the colon to specify a range of numbers. Typing

>>x= 1:4

will return

x=
        1         2            3     4

You can optionally give the colon a step size. For instance,

>>x=8:-1:5

will give

x=
            8     7        6         5

and

>> x = 0:0.25: 1.25

will return

x=
            0     0.25     0.5       0.75     1.0      1.25

The colon is a subtle and powerful operator, and we'll see more uses of it later.


3.3. Help

MATLAB has a fairly good help facility. The help function knows about all the commands listed in this manual.
Typing help function will tell you the syntax for the function, i.e. what arguments it expects. It will also give you a
short description of what the command does. If you think you are doing something right, but MATLAB claims you
are in error, try looking at the help for the functions you are using. Later, when we discuss writing your own
functions, we will show you how to include help info for your functions. This can be very useful for other people
using your function, or for your own use if you haven't used the function for a while.


3.4. Basic Matrix Constructors and Operators

MATLAB has a variety of built-in functions to make it easier for you to construct vectors or matrices without having
to enumerate all the elements.

The ones function will create a matrix whose elements are all ones. Typing ones(m,n) will create an m row by n
column matrix of ones. To create a discrete-time signal named y assigned to a vector of 16 ones, you would type y =
ones(1,16);. Also, giving ones a matrix as its only argument will cause it to return a matrix of ones the same size as
the argument. This will not affect the original matrix you give as an argument, though. If x = [ I 2 3 4; 0 9 3 8],
typing ones(x) will create a matrix of ones that is two rows by four columns. The zeros function is similar to the



                                                    Matlab-4
                                                                                                            Matlab Intro


ones function. Typing zeros(m,n) will create an m-by-n matrix of zeros, and zeros(x) will create a two-by-four
matrix of zeros, if x is defined the same way as above.

The max and min functions are used to find the largest and smallest values in a vector. If z = [1 2 -9 3 -3 -5], max(z)
will return 3. If you call max with a matrix as an argument, it will return a row vector where each element is the
maximum value of each column of the input matrix. Max is also capable of returning a second value: the index of
the maximum value in the vector. To get this, you assign the result of the call to max to be a two element vector
instead of just a single variable. If z is defined as above, [a b] = max(z) will assign a to be 3, the maximum value of
the vector, and b to be 4, the index of that value. The MATLAB function min is exactly parallel to max except that it
returns the smallest value, so min(z) will return -9.

Sum and prod are two more useful functions for matrices. If z is a vector, sum(z) is the sum of all the elements of z.
Similarly, prod(z) is the product of all the elements of z.

Often, it is useful to define a vector as a subset of a previously defined vector This is another use of the colon
operator. If we have z defined as in the min/max examples, z(2:5) will be the vector [2 -9 3 -3]. Again, remember
that MATLAB indexes vectors such that the first element has index one, not zero.

The MATLAB size function will return a two element vector giving the dimensions of the matrix it was called with.
If x is a 4 row by 3 column vector, size(x) will return the vector [4 3]. You can also define the result to be two
separate values as shown in the max example. If you type [m n] = size(x), m will be assigned to the value 4, and n to
the value 3. The length operator will return the length of a vector. If z is defined as 14 3 91, length(z) will return 3.
Basically, length(z) is equivalent to max(size(z)).


3.5. Element-wise Operations

We will often want to perform an operation on each element of a vector while doing a computation. For example,
we may want to add two vectors by adding all of the corresponding elements. The addition (+) and subtraction (-
operators are defined to work on matrices as well as scalars. For example, if x = [1 2 3] and y = [5 6 2], then x+y
will return [6 8 5]. Again, both addition and subtraction will work even if the elements are complex numbers.

Multiplying two matrices element by element is a little different. The * symbol is defined as matrix multiplication
when used on two matrices. To specify element-wise multiplication, we use, *. So, using the x and y from above,
x.*y will give [5 12 6]. We can do exponentiation on a series similarly. Typing x.^2 will square each element of x,
giving [ I 4 9]. Finally, we can't use / to divide two matrices element-wise, since / and \ are reserved for left and right
matrix "division." So, we use the./function, which means that y./x will give [5 3 0.6666]. Again, all of these
operations work for complex numbers.

The abs operator returns the magnitude of its argument. If applied to a vector, it returns a vector of the magnitudes
of the elements. For instance, if x = [2 -4 3-4*i -3 kid, typing

>> y = abs(x)

will return

y=
         2        4          5        3

The angle operator will return the phase angle of its operand in radians. The angle operator will also work element-
wise across a vector. Typing

>> phase = angle(x)



                                                     Matlab-5
                                                                                                         Matlab Intro


will give

phase =
            0       3. 14 1 6 -0.9273 - 1.5708

The sqrt function is another commonly used MATLAB function. As you might well expect, it computes the square
root of its argument. If its argument is a matrix or vector, it computes the square root of each argument. If we define
x = [4 -9 i 2-2*I], then typing

>> y = sqrt(x)

gives

y=
            2.00000 3.0000i 0.7071 i 1.5538 -0.6436i

MATLAB also has operators for taking the real part, imaginary part, or complex conjugate of a complex number.
These functions are real, imag and conj, respectively. They are defined to work element-wise on any matrix or
vector.

MATLAB includes several operators to round fractional numbers to integers. The round function rounds its
argument to the nearest integer. The fix function rounds its argument to the nearest integer towards zero, e.g. rounds
"down" for positive numbers, and "up" for negative numbers. ceil rounds its argument to the nearest integer towards
positive infinity, e.g. "up", and floor rounds its argument to the nearest integer towards negative infinity, e.g.
"down." All of these commands are defined to work element-wise on matrices and vectors. If you apply one of them
to a complex number, it will round both the real and imaginary part in the manner indicated. Typing

>> ceil(3.1 +2.4* i)

will return

ans =
            4.0000 + 3.0000i

MATLAB can also calculate the remainder of an integer division operation. If x = y * n + r, where n is an integer,
then rem(x,y) is r.

The standard trigonometric operations are all defined as element-wise operators. The operators sin, cos and tan
calculate the sine, cosine and tangent of their arguments. The arguments to these functions are angles in radians.
Note that the functions are also defined on complex arguments, which can cause problems if you are not careful. For
instance, cos(x+iy) = cos(x)cosh(y) - i sin(x)sinh(y). The inverse trig functions (acos, asin and atan) are also defined
to operate element-wise across matrices. Again, these are defined on complex numbers, which can lead to problems
for the incautious user. The arctangent is defined to return angles between pi/2 and -pi/2.

In addition to the primary interval arctangent discussed above, MATLAB has a full fourquadrant arctangent
operator, atan2. atan2(y,x) will return the angle between -pi and pi whose tangent is the real part of y/x. If x and y
are vectors, atan2(y,x) will divide y by x element-wise, then return a vector where each element is the four-quadrant
arctangent of corresponding element of the y/x vector.

MATLAB also includes functions for exponentials and logarithms. The exp operator computes e to the power of its
argument. This works element-wise, and on complex numbers. So, to generate the complex exponential with a
frequency of pi/4, we could type

>> n = 0:7;


                                                    Matlab-6
                                                                                                           Matlab Intro


>> s = exp(i*(pi/4)*n)

s=
         Columns 1 through 4
         1.0000 0.7071 + 0.7071 I          0.0000 + 1.0000i                -0.7071 + 0.7071 i
         Columns 5 through 8
         -1.0000 + 0.0000i        -0.7071 i - 0.7071 i              0.0000 - 1.0000i         0.7071 -0.7071 i

MATLAB also has natural and base-10 logarithms. The log function calculates natural logs, and log l0 calculates
base-10 logs. Again, both operate element-wise for vectors. Both also come complete with the now-familiar caveat
that they are defined for complex values, and that you should be careful about passing them complex arguments if
you don't know how complex logs are defined.


3.6. Graphics

MATLAB has several commands to allow you to display results of your computations graphically. The plot
command is the simplest way of doing this. If x is a vector, plot(x) will plot the elements of x against their indices.
The adjacent values of x will be connected by lines. For example, to plot the discrete-ime sequence that is a sinusoid
of frequency pi/6, you would type:

>>n=0:11;
>> y = sin((pi/6)*n);
>> plot(y)

Shortly after you enter the plot command, MATLAB will prompt you for a location to open the graphics window.
Just move the mouse to put the window where you want it, then click the left button. After MATLAB plots the
graph, it will wait for you to hit a key while the mouse is in either the MATLAB text window or graphics window
before it will continue with the MATLAB >> prompt. If you run the commands above, you will notice that the first
value graphed has an abscissa value of one, and not zero. This is because MATLAB indexes vector elements
beginning with one, not zero. Plot will use the values of y for the y-axis, and their indices for the x-axis. To obtain a
graph of y versus n, you would type

>> plot(n,y)

If plot gets two vectors for arguments, it creates a graph with the first argument as the abscissa values, and the
second vector as ordinate values. You can also change the type of line used to connect the points by including a
third argument specifying line type. The format for this is plot(x,y,'line-type') where line-type is - for a solid line, -
for a dashed line,: for a dotted line, and -. for a line of alternating dots and dashes. Whichever character you chose to
use must be enclosed by single quotes. For instance, plot(n,y,':') would create the same graph as above, except that
the points would be connected by a dotted line. The default line type is solid. Thinking carefully, we see that in this
case, it is misleading to connect the adjacent values by lines, since we are graphing a discrete-time sequence. Instead,
we should just put a mark to indicate each sample value. We can do this by using a different set of characters in
place of the line-type argument. If we use a period, each sample is marked by a point. Using a + marks each sample
with a + sign, * uses stars, o uses circles, and x uses x's. So, typing

>> plot(n,y,'o')

will plot the values of y against their indices, marking each sample with a circle. We can also plot several graphs on
the same axis. Typing

>> plot(x 1,y 1,x2,y2)




                                                     Matlab-7
                                                                                                          Matlab Intro


will graph y I vs. x 1 and y2 vs. x2 on the same axis. You can also include a specific line or point type for each graph
if you want by typing

>> plot(x 1I,y 1,'line-type 1',x2,y2,'1ine-type2')

where the line-types can be any of the characters listed above to specify line or point types.

You can also create plots with either or both axes changed to log-scale. All of these functions follow the same
conventions for arguments and line or point types as plot. Using loglog will create a plot with both axes as log
scales. For a plot with only one axis on log scale, semilogy will create a plot where the x-axis is linear and the y-axis
is logarithmic, while semilogx will have a linear y-axis and logarithmic x-axis.

You can use additional MATLAB commands to title your graphs, or put text labels on your axes. Typing title
('Beware of the aardvark') will label the current graph at the top with the text enclosed in single quotes. In this case,
that is "Beware of the aardvark." Likewise, you can label your x- and y-axes by typing xlabel ('This is the x-axis')
and ylabel ('This is the y-axis') respectively .

The axis command is used to control manually the limits and scaling of the current graph. Typing

>> a = axis

will assign a four-element vector to a. The first element is the minimum x-value, the second is the maximum x-value
for the current graph. The third and fourth elements are the minimum and maximum y-values, respectively. You can
set the values of the axes by calling the axis function with a four-element vector for an argument. These elements
should be your choices for the x- and y-axis limits, in the same order as specified above.
So, if you type

>> axis([-10 10 -5 5])

you will rescale the axis in the graphics window so the x-axis goes from -10 to 10, and the y-axis from -5 to 5. The
axis command can be stubborn sometimes, and round your limits up to new limits it finds easier to draw. There's
really nothing you can do about it. The hold command will keep the current plot and axes even if you plot another
graph. The new graph will just be put on the current axes as much as it fits. Typing hold a second time will toggle
the hold off again, so the screen will clear and rescale for the next graph.

You can use the subplot command to split the screen into multiple windows, and then select one of the sub-windows
as active for the next graph. The format of the command is subplot(xyn) where x is the number of vertical divisions,
y is the number of horizontal divisions, and n is the window to select for the first plot. Both x and y must be less
than or equal to two, and n must be less than or equal to x times y. For example, subplot( 121) will create two full-
height, half-width windows for graphs, and select the first, e.g. left, window as active for the first graph. After that,
unless you specifically indicate which window is active, MATLAB will cycle through them with each successive
plot. Typing subplot with no arguments will return the graphics window to its original, single-window state.

You can use the print command to get a hard copy of the current graphics window. Typing print ('printer-name') will
send the current graph to the printer whose name appears in single-quotes as the argument. This may take a minute
or two to start printing. MATLAB will just sit idle while generating the graphics file to dump to the printer. If no
printer is specified, MATLAB will send the printout to the default printer for your workstation. Note that MATLAB
can only send printouts to PostScript printers. Also, the implementation of print with the printer name as an argument
is Athena specific, and may not be found in another implementation of MATLAB .


3.7. Logical Operations




                                                     Matlab-8
                                                                                                              Matlab Intro


MATLAB allows you to perform boolean operations on vectors element-wise. For the purpose of boolean algebra,
MATLAB regards anything with a non-zero real part as true, and everything else as false. MATLAB uses & for the
boolean and operator, 1 for or, and for not. So, typing

>> [ 1 0 2 4] & [O 0 1 i]

gives

ans =
          0      0          1         0

while typing

>> [1 0 2 4] 1 [0 0 1 i]

will return

ans =
          1          0      1         1

In addition, you can run a cumulative boolean or or boolean and across all the elements of a matrix or vector. If v is
a vector or matrix, any (v) will return true if the real part of any element of v is non-zero. Similarly, all (v) will return
true if all the elements of v have non-zero real parts.

You can also compare two vectors element-wise with any of six basic relational operators, e.g. less-than (<), greater-
than (>), equal-to(==), not-equal-to (~=), less-than or-equal-to(<=), and greater-than-or-equal-to(>=). Typing

>>[1 2345]<= [543 2 11

returns

ans =
          1          1      1         0         0

We will see more uses of the relational operators when we discuss MATLAB programming control structures.


3.8 Interface Controls

When you first start running MATLAB, it is case-sensitive. This means that MATLAB distinguishes between upper
and lower case variable and function names. So, you can safely have two separate variables named aardvark, and
AARDVARK. If you type casesen, MATLAB will toggle to being non-case-sensitive. Typing it again will toggle
back to the original mode, e.g. case-sensitive.

MATLAB allows you to clear either the command (text) window, or the graphics window. The clc command will
clear the command window, and give you a fresh >> prompt. The clg command will clear the graphics window and
leave it blank.

You can see all the variables defined in your workspace by using the who command. The whos command will give
you the names of all the variables just like who does. In addition, it will tell you the size of each variable, if that
variable is complex, and the total bytes of space used by all your variables. If you run the who command, and see
that you have variables you are no longer using, you can use the clear command to remove obsolete variables. For
example, typing clear godzilla would delete the variable named godzilla.



                                                      Matlab-9
                                                                                                           Matlab Intro


MATLAB also defines some basic file manipulation utilities, so you can do these things without quitting and
restarting MATLAB. The dir command is identical to the Unix ls command. The chair is the same as cd for Unix,
type is Unix's cat, and delete is rm. You can also pass any other Unix command through by preceding it by a !. So,
typing !date will give you the current date and time. All pathnames and wildcards should work the same as they do
in Unix.

MATLAB's diary command allows you to make a transcript file recording your session. Typing diary filename will
record all the commands you type in filename, and will also record "most of the resulting output," according to the
MATLAB manual. Graphs will not be recorded, but almost all printed results will be. Typing diary off will turn the
transcript off, and diary on will turn it back on. The file created is in ASCII format, suitable for editing with Emacs
and including in other reports. In fact, this function was used to generate almost all the examples in this manual.

MATLAB includes commands that allow you to save all or some of your workspace so you can continue your
session later. Typing save filename will save all of your workspace in a compressed format in a file named
filename.mat. If you want to reload that workspace later to continue, you just type load filename. If you only want to
save some of the variables, you can give the save command the names of the variables to save. If you type

>> save aardvark moose wildebeest

MATLAB will save the variables moose and wildebeest in the file aardvark.mat.


3.9. Signal Processing Functions

MATLAB comes with several useful signal processing functions already defined. For example, if a and b are
vectors (a.k.a. discrete-time sequences), then conv(a,b) will convolve the two vectors. Typing aft(a) will return the
Discrete Fourier Transform of a, and idft(a) is the inverse DFT a. fft(a) will return the Fast Fourier Transform of a,
and ifft(a) is the Inverse FFT. If a is not a radix-two in length, fft and ifft will zero-pad it so that the number of
samples in the sequence is a power of two.

If we define a and b to represent a system described by the difference equation:

         y(n) =: )( i ) *x(n)           + b(2) Din- 1 ) + ...+ b(nb)*x(n-nb+l)

                                - a(2)*y(n-1) -…-a(na)*y(n-na+1)

typing

>>filter(b,a,x)

will return the sequence that is the result of filtering x with that the system defined by that difference equation. The b
and a coefficient vectors should be ordered by ascending value of delay. If a( I ) is not I, filter will normalize a so
that it is by dividing all of a by a( 1).

If we define a and b for a system as above, we can also use the freqz command to evaluate the Z-transform of the
system. There are several ways to input values depending on how you want to evaluate the transform. Typing

>> freqz(b,a,n)

evaluate the z-transform at n evenly-spaced points around the upper half of the unit circle.
If you type

>> freqz(b,a,n 'whole')



                                                      Matlab-10
                                                                                                        Matlab Intro


MATLAB will evaluate the transform at n evenly-spaced points around the whole unit circle. If you assign the result
of freqz to a single variable, you will get back the values at the frequencies, which may be complex. If you assign
the result to a two-element vector, the first element will be assigned to the complex values of the samples, while the
second element will be assigned to a vector of the frequencies the z-transform was evaluated at. For example, to
look at the very simple system y[n] = x[n - 1], you would type:

>>a= [1];
>>b= [0 1];
>> [h w] = freqz(b,a,16);

After doing this, h would be defined as the complex-valued samples of the z-transform, and w would be
the frequencies at which the z-transform was evaluated to get those values. If you choose n to be a power of two,
freqz will run much faster, since it will use the fft operator. If you don't want evenly-spaced samples around the
unit-circle, you can explicitly specify at which frequencies the z-transform should be evaluated. To do this, type
freqz(b,a,w) where w is a vector of the frequencies (in radians) at which to evaluate the z-transform.


3.10. Polynomial Operations

Vectors can also be used to represent polynomials. If you want to represent an Nth-order polynomial, you use a
length N+1 vector where the elements are the coefficients of the polynomial arranged in descending order of
exponent. So, to define y = x2 - 5x + 6, you would type:

>> y = [1 -5 6];

The MATLAB roots function will calculate the roots of a polynomial for you. If we use the y from above,

>> roots(y)

will return

ans =
         3                  2

MATLAB also has the poly function, which takes a vector and returns the polynomial whose roots are the elements
of that vector.

You can use MATLAB to multiply two polynomials using the cony function described above. The convolution of
the coefficient vectors is equivalent to multiplying the polynomials. The polyval function can tell you the value of a
polynomial at a specific point. For example, polyval(y, 1) would return 2. polyval also works element-wise across a
vector of points, returning the vector where each element is the value of the polynomial at the corresponding element
of the input vector.


3.11. Control Structures

MATLAB includes several control structures to allow you to write programs. The for command allows you to make
a command or series of commands be executed several times. It is functionally very similar to the for function in C.
For example, typing

for i= 1:4
        i
end



                                                   Matlab-11
                                                                                                               Matlab Intro


will cause MATLAB to make the variable i count from 1 to 4, and print its value for each step. So, you would see

i=
           1
i=
           2
i=
           3
i=
           4

Every for command must have a matching end statement to indicate which commands should be executed several
times. You can have nested for loops. For example, typing

form= 1:3
        for n= 1:3
                 x(m,n)=m+n*i;
   end
end

will define x to be the matrix

x=
           1.0000 + 1.0000i 1.0000 + 2.0000i 1.0000 + 3.0000i
           2.0000 + 1.0000i         2.0000 + 9.0000i          2.0000 + 3.0000i
           3.0000 + 1.0000i         3.0000 + 2.0000i 3.0000 + 3.0000i

The indentations in the for structure are optional, but they make it easier to figure out what the commands are doing.

The if command lets you have programs that make decisions about what commands to execute. The basic command
looks like

if a > 0
           x=a^2;
end

This command will assign x to be the value of a squared, if a is positive. Again, note that it has to have an end to
indicate which commands are actually part of the if. In addition, you can define an else clause which is executed if
the condition you gave the if is not true. We could expand our example above to be

if a>0
           x = a^2;
else
           x = -a^2
end

For this version, if we had already set a to be 2, then x would get the value 4, but if a was -3, x would be -9. Note
that we only need one end, which comes after all the clauses of the if. Finally, we can expand the if to include
several possible conditions. If the first condition isn't satisfied, it looks for the next, and so on, until it either finds an
else, or finds the end. We could change our example to get

if a>0
          x = a^2;
else if a == 0


                                                      Matlab-12
                                                                                                              Matlab Intro


          x = i;
else
          x = -a^2
end

For this command, it will see if a is positive, then if a is not positive, it will check if a is zero, finally it will do the
else clause. So, if a positive, x will be a squared, if a is 0, x will be i, and if a is negative, then
x will be the negative of a squared. Again, note we only have a single end after all the clauses.

The third major control structure is the while command. The while command allows you to execute a group of
commands until some condition is no longer true. These commands appear between the while and its matching end
statement. For instance, if we want to keep squaring x until it is greater than a million, we would type

while x < 1000000
         x = x^2;
end

If we start with x = 2, this will run until x is 4.295 x 109. Everything between the while line and the end will be
executed until the boolean condition on the while line is no longer true. You have to make sure this condition will
eventually stop being true, or the command will never finish. If it is not initially true, the commands will never be
executed.

The pause command will cause MATLAB to wait for a key to be pressed before continuing. This is useful when you
are writing your own functions.

Sometimes you will want to terminate a for or while loop early. You can use the break command to jump out of a for
or while command. For example, you could rewrite our while example from above to be:

while 1
         if x > 1000000
                  break;
       end
                  x = x^2
end

which will have exactly the same effect.


3.12. Functions

Finally, we come to the apex of our discussion: writing your own functions for MATLAB. You do this using M-
files. An M-file is an ASCII text file that has a filename ending with .m, such as aardvark.m. You can create and edit
them from Emacs. There are two classes of M-files, functions and scripts. Functions are more interesting, so we'll
talk about them first. An M-file is a function if the first word in it is function. A function can just take several
arguments, or none at all, and return any number of values. We will look at several examples grouped by the number
of values they return. The first line of the file specifies the name of the function, along with the number and names
of input arguments and output values.

3.12.1 Functions Returning No Values

A common example of a function that doesn't return any values is one that draws graphs. It just draws the graphs,
then finishes. Here is an example of such a function

function stars(t)


                                                      Matlab-13
                                                                                                            Matlab Intro


%STARS(T) draws stars with parameter t
n=t*50;
plot(rand(1,n), rand(1,n),',')
% that line plots n random points
title ('My God, Its Full of Stars!’);
% label the graph

This will draw a random sprinkling of dots across the screen. The first line defines this as a function names stars that
takes one argument named t, and doesn't return anything. The next line is the help comment. Any comments coming
immediately after the first line will re returned by help stars, which would be

%STARS(T) draws stars with parameter t

for this function. A line of comments is indicated by the % character. You can have as many of these as you want,
and the help command will print all of them. Next, the function defines an internal variable named n to be Fifty times
t. This n is totally unrelated to any variable already defined in the main MATLAB workspace. Assigning this value
will not alter any n you had already defined fore calling the stars function. You can also see how we put a comment
in the middle of the function indication which command actually drew the stars.

Sometimes, you will need to write several versions of a function before it works properly. When you use an M-file
function for the first time during a session, MATLAB reads it in, compiles it, and then remembers that version, If
you change the M-file after using the function, MATLAB won't see it. It will just use the first version it compiled. To
remove the first version, and force MATLAB to read the new one in, you should use the clear command. If you type
clear orangutan, MATLAB will erase the function orangutan from MATLAB's previously know functions, so the
next time you call orangutan it will read in your new version of orangutan. Make sure you do this when you fix a bug
in a function, or you will be very confused about why MATLAB is ignoring your changes.

3.12.2 Functions Returning One Value

Next, we look at an example of a function that returns one value.

function y = fact(n)
%Y = FACT(N) computes the factorial of n;
y= 1;
for i = 2:n\
                   y=y*i;
end

This function will calculate the factorial of its argument. The first line indicates that this is a function of one
argument n, and should return the value of the variable y for its answer. The for loop will repeatedly multiply y by
every value between 2 and n. Whatever value is finally in y will be returned as the result of the function. For this
function, it is a scalar, but functions can also return vectors or matrices. Again, note that the variables y, i, and n
have absolutely no effect on any variables of the same name in the main MATLAB workspace.

3.12.3 Functions Returning More Than One Value

If you want to return more than one argument, you can do it by having the function return a vector of values. The
following function is an example of a function that does this. For instance, the following function returns two
vectors. The first vector is the prime factors less than 10 of the argument. The second indicates how many times
each of these factors is used.

function [factors, times] = primefact (n)
%[FACTORS TIMES] = PRIMEFACT(N)



                                                     Matlab-14
                                                                                                            Matlab Intro


find prime factors of n

primes = [2 3 5 7]
        for i= 1:4
                   temp = n;
                           if (rem(temp,primes(i)) ==0)
                                     factors = [factors primes(i)];
                                     times = [times 0];
                                              while (rem(temp,primes(i)) ==0)
                                                        temp = tamp/primes(i);
                                                        times(length(times)) = times(length(times))+1;
                                              end
                           end
end

If we call this function with just one argument, i.e. a = primefact( 10) we will get back the vector of prime factors,
but not the vector indicating how many times each factor appears in the number. To get both vectors, we should call
the function in this manner:

>>[a b] = primefact( 180)

a=
         2        3         5
b=
         2        2         1

This way, we get both vectors returned: the primes in a, and the number of times each prime was used in b. From
these results, we see that 180=2x2x3x3x5.

3.12.4 Script M-files

As we mentioned earlier, there is a second kind of M-file. The script type M-file is just a list of commands to
execute in sequence. This differs from a function M-file in that no arguments are needed. Also, the variables inside a
script file are the same ones as in the main MATLAB workspace. If I have a variable named n = 1000, then execute
a script that includes the line n = 2, my variable will now be 2, and not 1000. To create a script file, just create a file
with Emacs that contains the commands you want executed. A script file should not have the word function in the
first line, and doesn't need the comments for the help command. The filename should still end in .m though.


3.13. Advanced Features

The features listed in the following sections are not essential for using MATLAB on Athena, but are included for the
more curious users who want to push MATLAB as much as possible.

3.13.1 Selective Indexing

Sometimes, you only want to perform an operation on certain elements of a vector, such as all the elements of the
vector that are less than 0. One way to do this is a for loop that checks to see if each element is less than zero, and if
so, does the appropriate function. However, MATLAB includes another way to do this. If you say

>>x(x<0) = -x(x<0)

MATLAB will change all the negative elements of the vector x to be positive. The following sequence of commands
illustrates this:


                                                     Matlab-15
                                                                                                          Matlab Intro



>>x = [-3 -2 0 2 4]

x=
         -3       -2       0         2        4

>>x(x<0) = -x(x<0)

x=
         3        2        0         2        4

Though this notation can be more confusing than a for loop, MATLAB is written such that this operation executes
much, much faster than the equivalent for loop.

You can also perform operations on a vector conditionally based upon the value of the corresponding element of
another vector. For instance, if you want to divide two vectors element-wise, you have to worry about what happens
if the denominator vector includes zeros. One way to deal with this is shown below.

>>x=[32024]
x=
        3         2       0     2             4
>>y= [1 1 1 1 1]
y=
        1         1       1     1             1
>>q = zeros( 1,length(y))
q=
        0         0       0     0             0
>>q(x~=0) = y(x~=0) ./ x(x~=0)
q=
        0.3333 0.5000 0 0.5000 0.2500

You can perform this type of conditional indexing with any boolean operator discussed earlier, or even with boolean
operators on the results of functions on elements of vectors. For example

>>q((x<=3) & (q<=0.4)) = q((x<=3) & (q<=0.4)) + 14
q=
        14.3333                 0.5000 0          0.5000 0.2500

3.13.2 Functions with Variable Number of Arguments

Anytime you call a function, MATLAB defines a variable inside that function called margin. margin is the number of
arguments with which the function was called. This allows you to write functions that behave differently when called
with different numbers of arguments. If you specify the function rhino such that the first line of its M-file file reads:

function hippo = rhino(a,b,c,d)

MATLAB will not get upset if you call rhino with only two arguments. It will just assume the last two arguments
were optional, and not used. MATLAB will set nargin = 2, and execute the function. If the function tries to do
something using the variables c or d, MATLAB will generate an error message. MATLAB assumes that you will use
nargin to avoid referring to any optional arguments that weren't supplied.

3.13.3 Aspect Ratio Control




                                                    Matlab-16
                                                                                                        Matlab Intro


As with many computers, MATLAB's graphing system is not perfectly scaled. MATLAB does allow you switch
between a perfectly square aspect ratio and the normal aspect ratio. Typing axis('square') will give you a truly square
aspect ratio, while axis('normal') would flip you back to MATLAB's usual aspect ratio. If you don't know what
aspect ratios are, you really don't need to worry.




                                                   Matlab-17

								
To top