MATLAB Tutorial III – Variables, Files, Advanced Plotting

MATLAB Tutorial III ? Variables, Files, Advanced Plotting

A. Dealing with Variables (Arrays and Matrices)

Here's a short tutorial on working with variables, taken from the book, Getting Started in Matlab. It is highly recommended that you obtain this book as it will make your life in Matlab easier. Variables in Matlab can have any name, but if the variable has the same name as a function, that function will be unavailable while the variable exists. Try typing the following into Matlab (without comments):

>> theta=acos(-1) theta =

% Assign arccos(-1) to theta % Matlab uses radian units for all % trig functions

3.1416

>> theta-pi ans =

Creating and Working With Matrices

% Note that pi is built into % Matlab, and more precision % is kept internally than is % printed on the screen

In Matlab, there are a number of ways to create matrices. First, let's look at how to generate vectors (call them x and y), which are 1xN matrices. We will make x go from 0 to 3*pi. Type the commands.

>> x=0:0.1:3*pi;

>> x = linspace(0,3*pi,100); >> y=exp(x/5);

% Create vector x from 0 to 3*pi in % increments of 0.1 % But, could also use: % Create vector x from 0 to 3*pi with % 100 steps exactly % Compute exp(x/5) for each x value, and % assign to a y value % Note that there is no loop here, but % y now has as many entries as x!

Now, let's try making true two-dimensional matrices (MxN); start with a 3x3 matrix typed on the command line:

>> x = [1 4 7; 2 5 8; 3 6 9]; >> x = [1,4,7 2,5,8 3,6,9];

% semicolons denote changes of row % Matlab's command line knows % the matrix is not finished % until the closing ']'

In any case, the result is the same, the following 3 x 3 matrix stored as the variable x:

>> x x =

1 4 7 2 5 8 3 6 9

% Display the current value of x

You should notice that square brackets ([ ]) enclose the matrix, spaces or commas (,) denote elements within a row, and either a semicolon (;) or a hard return denote rows.

1

Matlab also has functions to produce matrices of zeros and ones of a specified size:

>> zeros ( [3 3] ) ans =

% Produce matrix of all zeros, % size of 3x3

0 0 0 0 0 0 0 0 0

>> zeros(3, 3)

% Alternate size format of above

ans =

0 0 0 0 0 0 0 0 0

>> zeros(2)

% Matrix of zeros, size 2x2

ans =

0 0 0 0 >> zeros([1 2])

% Row vector of zeros, 2 long

ans = 0 0

>> zeros([2 1])

% Column vector of zeros, 2 long

ans =

0 0

>> ones(2, 2)

% Same as zeros(), but matrix filled with 1

ans =

1 1 1 1

To access matrix elements, specify the rows and columns we are interested in. Remember how we used the colon (:) to fill in numbers when we plotted numbers from 1 to 5 in the first section? We will use that again. The syntax is x(row,col) so, for example, if we want the to assign the element in the third row, first column to the variable y, we type:

>> y = x(3,1);

% Assign row 3, col 1 element of x to y

2

To specify an entire row or column, use a colon (:) in place of the row or column number. So, if we want the entire second column, we would type:

>> y = x(:,2);

% Assign all rows, col 2 elements to y

Now let's try a short exercise to use matrices and matrix operations.

1. Create a vector of the integers from 1 to 5 and name it a.

2. Add 1 to all the elements of a, and store in a.

3. Create a vector of the integers from 5 to 1 and name it b.

4. Add a to b and store the result in c.

Here is a transcript (diary) of a MATLAB session implementing the exercise:

>> a=1:5; >> a=a+1

% vector of 1 to 5, increment 1 % add 1 to all elements of a

a =

2 3 4 5 6

>> b=5:-1:1

% vector of 5 to 1, increment -1

b =

5 4 3 2 1

>> c=a+b c =

% add a and b, store in c

7 7 7 7 7

Note that all vectors used so far have been row vectors; the vector is a row from a matrix (one row, many columns). There are also column vectors, which are displayed vertically (many rows, one column). To transform a row vector to a column vector (or back), use the transpose operation; in Matlab, this is denoted by ' after the vector (or matrix) name.

>> a'

ans =

2 3 4 5 6

Matlab, being focused on matrix operations, always assumes operations are matrix operations unless told otherwise. In the exercise above, we added a scalar to a matrix, which is the same as adding a scalar

3

to every element of the matrix. In general, though, Matlab will do matrix addition, multiplication, division, etc.

To make Matlab apply an operation to each element individually (rather than use matrix operations), use a .(period) before the operator; for example, to square each element of a vector, we use:

>> a=1:5; >> a.*a

ans =

% the . makes Matlab apply the * % to each element as a set of scalar % operations, NOT matrix multiplication

1 4 9 16 25

If there is no ., Matlab assumes the intent is a matrix operation, which won't work for two row vectors:

>> a*a ??? Error using ==> * Inner matrix dimensions must agree.

If the intent really is to do a matrix multiplication of a by a, we need to take the transpose of the second vector:

>> a*a'

ans =

55

Since a is a 1x5 vector, a' (transpose of a) is a 5x1 vector. When multiplied, the result is a 1x1 vector, which is a scalar, as seen here.

Keeping track of matrix dimensions can be difficult, but is extremely important. Fortunately, Matlab will normally produce errors when your code tries to do something mathematically incorrect.

B. Loading and Saving Data Files

(You do not need to try the commands in this section; just read through the examples.)

The key to loading data into Matlab is to remember that Matlab only uses matrices. That means that if you want to easily read a data set into Matlab, all of the rows must have the same number of elements, and they must all be numbers.

Most commonly, you'll be dealing with a text (ASCII) file. If you have a set of data on disk in a file called points.dat, then to load it, you would type:

>> load points.dat

This will load your data into the Matlab variable points. Let's assume that the file points.dat contains two columns, where column 1 is height and column 2 is distance. To break apart the data matrix points into something more meaningful, we use:

>> height = points(:,1); >> distance = points(:,2);

This creates a vector height from the first column (all rows), and distance from the second column.

4

To save the same data into an ASCII file called mydata.dat, we use either:

>> save mydata.dat height distance ?ascii

% common form for % command line

or

>> save('mydata.dat', 'height', 'distance', '-ascii'); % common form for use in scripts %and functions

The -ascii flag is important here; it tells Matlab to make the file in ASCII text, not a platformindependent binary file. Without the flag, the file would be unreadable with standard editors. Text is the most portable and editable format, but is larger on disk. Matlab's binary format is compatible across all platforms of Matlab (Windows, UNIX, Mac, etc.), and is more compact than text, but cannot be edited outside of Matlab.

You will note that when Matlab saves files in ASCII format, it uses scientific notation whether it needs it or not.

More powerful and flexible save and load schemes exist in Matlab; they use the fprintf() and fscanf() functions along with fopen() to control file output. We will be using fscanf/fprintf later in the semester to read in data from measurement instruments and to send commands to instruments.

C. Advanced Plotting

1. Controlling Symbol and Line Characters and Colors

As we have seen, plot(x,y,s) will plot y as a function of x using linestyle s, where s is a 1 to 3 character string (enclosed by single quotes) made up of the following characters.

y yellow m magenta c cyan r red g green b blue w white k black

. point o circle x x-mark + plus - solid * star : dotted -. dashdot -- dashed

For example, to create a plot of x versus y, using magenta circles, type the command plot(x,y,'mo');. To plot more than one line, you can combine plots by typing plot(x1,y1,s1,x2,y2,s2,...);.

2. Printing Plots and Saving Figures as Graphics Files

You can print a hard copy of a MATLAB plot either by choosing print from the File menu at the top of the figure, or by typing print at the MATLAB command line. (The later approach seems to work better on many of our computers.) You can also save plots as graphics files; from the File menu near the top of the figure, choose Save as... and then choose a file name and a graphics file type. You should save plots as .eps files for importing into TeX documents, and as .jpg or .png for Word.

5

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download