19
Tutorial #2 - Graphics and advanced Matlab features Importing and exporting data To do anything significant in Matlab, you have to load in data files and then save your output. There are two ways to load and save data in Matlab; either use the high level, easy to use functions, or the low level, harder to use functions. For the work I do, the high level functions I almost exclusively use for loading my data files; rarely is there a time when I need to use the low level functions to do this. However for saving my output I like to use the low level functions since they give me more flexibility and can create smaller output files. Loading and saving data with high level functions Load, Save with mat files There are two types of files you can use with these commands, .mat files and text files. Mat files are binary Matlab files which will save all the variables in the current workspace to a disk file. Matlab can then load a .mat file and add the variables in it to your current workspace. If some variables in your current workspace have the same name as variables in the .mat file, the .mat file variables will overwrite the variables currently in the workspace. var1 = 10; var2 = 20; whos Name Size Bytes Class var1 1x1 8 double array var2 1x1 8 double array Grand total is 2 elements using 16 bytes save myvars var1=100; var3 = 30; load myvars whos Name Size Bytes Class var1 1x1 8 double array var2 1x1 8 double array var3 1x1 8 double array Grand total is 3 elements using 24 bytes var1 var1 = 10 Load, Save with text files load and save can also be used with text files. The format for load is load(‘filename’). If you have the name of the file in a variable, then it becomes load(var). The load function can read text files with spaces, tabs or commas for delimiters. The format of the save function is save filename matrix –ascii . Filename is the name of the file you want saved and matrix is the name of the vector or matrix you want saved. What I don’t like about the save function is it is very wasteful of disk space if the data you are saving is mainly integer data or data with just a few digits of precision. For the next example, I created a file called mixed.dat. The first delimiter is a space, the second is a tab and the third is a comma. Be sure the file is in one of the directories in your Matlab path. Here is it’s contents: 1 10 100,1000 2 20 200,2000 3 30 300,3000 4 40 400,4000 5 50 500,5000 >> fname = ‘mixed.dat’; >> data = load(fname) data = 1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000 >> save ‘mixedout.dat’ data –ascii; Here are the contents of the file written out by the save function: Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm 1 of 19 1/3/2015 11:08 AM

Tutorial #2 - Graphics and Advanced Matlab Features

  • Upload
    azizcr

  • View
    260

  • Download
    4

Embed Size (px)

Citation preview

Page 1: Tutorial #2 - Graphics and Advanced Matlab Features

Tutorial #2 - Graphics and advanced Matlab features

Importing and exporting dataTo do anything significant in Matlab, you have to load in data files and then save your output. There are two ways to load and save data

in Matlab; either use the high level, easy to use functions, or the low level, harder to use functions. For the work I do, the high levelfunctions I almost exclusively use for loading my data files; rarely is there a time when I need to use the low level functions to do this. However for saving my output I like to use the low level functions since they give me more flexibility and can create smaller output files.

Loading and saving data with high level functions

Load, Save with mat filesThere are two types of files you can use with these commands, .mat files and text files. Mat files are binary Matlab files which will save

all the variables in the current workspace to a disk file. Matlab can then load a .mat file and add the variables in it to your currentworkspace. If some variables in your current workspace have the same name as variables in the .mat file, the .mat file variables willoverwrite the variables currently in the workspace.

var1 = 10;var2 = 20;whos Name Size Bytes Classvar1 1x1 8 double arrayvar2 1x1 8 double array

Grand total is 2 elements using 16 bytes

save myvarsvar1=100;var3 = 30;load myvarswhos Name Size Bytes Class var1 1x1 8 double arrayvar2 1x1 8 double arrayvar3 1x1 8 double array

Grand total is 3 elements using 24 bytes

var1 var1 =10

Load, Save with text filesload and save can also be used with text files. The format for load is load(‘filename’). If you have the name of the file in a variable,

then it becomes load(var). The load function can read text files with spaces, tabs or commas for delimiters. The format of the savefunction is save filename matrix –ascii. Filename is the name of the file you want saved and matrix is the name of the vector or matrix

you want saved. What I don’t like about the save function is it is very wasteful of disk space if the data you are saving is mainly integerdata or data with just a few digits of precision. For the next example, I created a file called mixed.dat. The first delimiter is a space, thesecond is a tab and the third is a comma. Be sure the file is in one of the directories in your Matlab path. Here is it’s contents:

1 10 100,1000 2 20 200,2000 3 30 300,3000 4 40 400,4000 5 50 500,5000

>> fname = ‘mixed.dat’;>> data = load(fname)

data =

1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000

>> save ‘mixedout.dat’ data –ascii;

Here are the contents of the file written out by the save function:

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

1 of 19 1/3/2015 11:08 AM

Page 2: Tutorial #2 - Graphics and Advanced Matlab Features

1.0000000e+000 1.0000000e+001 1.0000000e+002 1.0000000e+0032.0000000e+000 2.0000000e+001 2.0000000e+002 2.0000000e+0033.0000000e+000 3.0000000e+001 3.0000000e+002 3.0000000e+0034.0000000e+000 4.0000000e+001 4.0000000e+002 4.0000000e+0035.0000000e+000 5.0000000e+001 5.0000000e+002 5.0000000e+003

As you can see, it is much larger and harder to read then the first file. This is why I use the low level functions for writing out data files.

Dlmread

The dlmread function is an enhanced form of the load function. By default it can load text files which contain spaces, tabs or commasas delimiters. However if you have some strange file format which has some other delimiter, you can specify what that delimiter is. The

dlmread function will also allow you to read a subset of the data within the file. This is convenient when you have a data file with headerinformation and you want to just read the data after the header. You can also read a subset of the data file using Excel’s A1 style notation.

The format of the dlmread function is:

matrix = dlmread(filename, delimiter, firstRow, firstColumn)

Be careful in that the FirstRow and FirstColumn values start from 0, not 1. If you do not specify the row and column, the entire file willbe read. Here is an example data file called Header.dat, which uses a space for a delimiter character:

sample rate = 100time = 10:32:54date = 10/24/200111 10 100 100022 20 200 200033 30 300 300044 40 400 400055 50 500 5000

fname = ‘header.dat’; data=dlmread(fname, ‘ ‘, 3, 1)

data =

10 100 1000 20 200 2000 30 300 3000 40 400 4000 50 500 5000

You can see we skipped reading the first 3 lines of data.

data=dlmread(fname, ‘ ‘, 3, 2) Now only read the second and third columns

data =

100 1000 200 2000 300 3000 400 4000 500 5000

Now we skipped reading the first 3 lines of data and also did not readthe first column of data.

dlmwrite

This is much like the save function, but you can also specify the output delimiter to use and you can save only a subset of your matrix if

you choose. The dlmwrite function has the following syntax:

dlmwrite(filename, matrix, delimiter, firstRow, firstColumn)

Again, the row and column start from 0, not 1 like the dlmread function. In this case, the firstRow and firstColumn specify the startingpoint to save data in the matrix. In the next example, I’ll read in the header.dat file with dlmread, add a constant to the last column and

write out the numeric data with dlmwrite.

data=dlmread('header.dat', ' ', 3, 1) Read in the data, skipping the 3 header lines

data =

10 100 1000 20 200 2000 30 300 3000 40 400 4000 50 500 5000

data(:,3) = data(:,3) + 0.01 Now add 0.01 to all values in the last column

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

2 of 19 1/3/2015 11:08 AM

Page 3: Tutorial #2 - Graphics and Advanced Matlab Features

data =

1.0e+003 *

0.0100 0.1000 1.0000 0.0200 0.2000 2.0000 0.0300 0.3000 3.0000 0.0400 0.4000 4.0000 0.0500 0.5000 5.0000

Notice how Matlab formatted the display of data. Not too easy toread.

format bank Change the output formatdata

data =

10.00 100.00 1000.01 20.00 200.00 2000.01 30.00 300.00 3000.01 40.00 400.00 4000.01 50.00 500.00 5000.01

This is better

dlmwrite('dlmout.dat', data, '\t', 1, 1); Now save the file, using the tab character as a delimiter

Here is the output file produced by the dlmwrite function. Notice the output file is formatted more nicely then was the one using thesave function.

10 100 1000.0120 200 2000.0130 300 3000.0140 400 4000.0150 500 5000.01

textread

This function should be able to read in any file you throw at it. One of the nice things about textread is you can read in files whichcontain a mixture of strings and numbers, and you can place each column from the file into a separate vector if you like. One concept youneed to understand is the format string. This is also true of the low level functions, which also use a format string. A format string tells thefunction how the data being read in from the current column should be stored. For instance, character data and string data are internallystored in very different ways. I won’t get into the details of this, since you should never have to worry about this. A format string canbecome very complex, and you can do some very cool things with it, but the basic format string is pretty simple to understand.

A format string starts with a % character, which is then followed by a character which represents the type of data you are reading in. Intutorial one I talked about the general data types in Matlab such as scalars, strings, vectors and matrices. You can also have multiple formatcharacters within one format string, and the format string is enclosed in single quotes. Each vector or matrix is composed of scalar values,which can be further broken down as follows:

%d 10, -1, +2003, 0 integers – whole numbers, no decimal points%f 10.5, -1.345, 1e-3 floating point – fractional numbers%c a, b, z, r read a character or whitespace, return in a char array.%s sue, rate, cat read a whitespace separated string (returns cellstr)

I going to skip around here a bit and as an example I will load in the file I create in the next section. Notice that since there are fourcolumns of data, I have four different format characters in the format string.

[subs,col1,col2,col3] = textread('subdata.dat','%d%d%f%f', 'headerlines', 1);[subs col1 col2 col3]

ans =

101.0000 1.0000 12.0000 101.6000105.0000 5.0000 7.3000 124.8700107.0000 3.0000 40.0000 154.8000109.0000 7.0000 -1.0000 70.4000

xlsread

Will read Excel’s .xls files directly into Matlab. You can either read in the first sheet in the xls file(the default), or you can pick thesheet you want to read into Matlab. This function is very handy if you have any data stored in Excel spreadsheets you want to read into

Matlab. Using xlsread saves you from having to export the excel file as an ascii file. I’ve created an Excel file called sheets.xls whichcontains two sheets called normal and transposed.

The format of the xlsread function is:

xlsread(filename, sheetname)

sheet1 = xlsread('sheets.xls')

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

3 of 19 1/3/2015 11:08 AM

Page 4: Tutorial #2 - Graphics and Advanced Matlab Features

sheet1 =

1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000

sheet2 = xlsread('sheets.xls', 'transposed')

sheet2 =

1 2 3 4 5 10 20 30 40 50 100 200 300 400 500 1000 2000 3000 4000 5000

xlsfinfo

This function will return the sheet names in the spreadsheet. This is a handy function when you want to write a program whichprocesses each sheet in a spreadsheet. You can use this function to get a list of the sheet names, then with a for loop read each sheet intoMatlab.

The format for the xlsfinfo function is:

[str, sheets] = xlsfinfo(filename)

[str, sheets] = xlsfinfo(‘sheets.xls’)

str =

Microsoft Excel Spreadsheet

sheets = 'normal' 'transposed'

Loading and saving data with low level functionsAs I mentioned earlier, I find very little reason to use the low level functions for reading in data, with the number of functions Matlab

has for doing this. I do find though that to output a data file in the exact format you want in many cases requires you to use the lower levelfunctions to do this. To read data you use the fscanf function. To write data you use the fprintf function. Both of these functions use the

format string concept mentioned above with textread. You need to open the file before you write to it, and you need to close the file when

you are done with it. To open a file you use the fopen function. To close a file you use the fclose function. All four functions operate with

a concept called the file handle. The file handle is a data structure which holds information about the file you opened with fopen. You thenneed to pass the file handle to fprintf, fscanf and fclose in order for them to work with that file. It is very important to close the file whenyou are done, since there are a limited number of file handles(512). While this is a lot, if you are reading many files in a loop and not closingthe files, you could run out of file handles. Very strange things start happening to Matlab when it runs out of file handles. So in order tosave yourself much possible frustration, always close your files when you are done!

fopen

The fopen function has the following format:

fid = fopen(filename, permission)

The value returned from the fopen function is the file handle I talked about above. Filename is of course the name of the file to read orwrite. The permission parameter specifies how the file will be opened and will be operated upon. Note that the characters for thisparameter are case sensitive. Note that filename and permission need to be enclosed in single quotes, unless you are using variables insteadof literals. There are three different strings for the permission parameter. There are actually more, but these three should work for you 99%of the time.

rt Read in a text file

wt Write to and if need be create the text file. If the file already exists, it will be overwritten. You will notbe asked if you want to replace the file.

at Append to and if need be create the text file. If the file already exists, any data written to the file willbe added to the end of the file.

The second character ‘t’ is very important. This tells Matlab you are reading a text file as opposed to a binary file. If you are reading orwriting to a binary file, then don’t use the ‘t’. Again, the above three strings need to be typed exactly as shown; no caps!

Now let me give some examples of using fopen and fclose:

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

4 of 19 1/3/2015 11:08 AM

Page 5: Tutorial #2 - Graphics and Advanced Matlab Features

fpin1 = fopen('spaces.dat') Open the file spaces.dat and create file handle 1

fpin1 =

3File handle number is 3

fpin2=fopen('tabs.dat') Open the file tabs.dat and create file handle 2

fpin2 =

4File handle is now 4

fclose(fpin1); Close the file and delete the first file handlefclose(fpin2); Close the file and delete the second file handlefpin1 = fopen('spaces.dat'); Open the files againfpin2=fopen('tabs.dat'); fclose(‘all’); This alternate form will close all open files at once

A couple of things to note here. Your file file handle did not start from 1; this means Matlab is internally using file handles 1 and 2 forit’s own use. I also gave each file it’s own variable, so I could distinguish the two. If I had given the file tabs.dat the same file handlevariable name as spaces.dat, then I would have lost the link to the file spaces.dat. The only time you should reuse the same variable namefor different file handles is when you know the previous file has been closed first. If fopen returns a value of -1 then there is an error. Usually it is because the file could not be opened. Also note that I had two files opened at the same time. You can have multiple files openat one time; just be sure you close them. Here is abbreviated form is how you read from and write to files using the low level functions:

Reading from a file Writing to a filefid = fopen('test.dat', 'rt'); fid = fopen('filename', 'wt' or 'at');fscanf(fid, 'format string', list of variables); fprintf(fid, 'format string', list of variables);fclose(fid); fclose(fid);

fprintf

The format of the fprintf function is:

fprintf(file handle, format string, list of variables)

This function is used to write data to a file. It can have a multiple number of parameters, depending on how many variables you want towrite out at a time. The first parameter is the file handle, the second parameter is the format string, each additional parameter represents a

variable you want to output with that fprintf function. The number of format characters in the format string must equal the number ofvalues you want to output. Here are the most common format characters you can use in the format string.

\n Use this to go to the next line in your file\t Insert a tab into the file.%d Write out an integer number

%f Write out a floating point number. You can precede the f with a .x where x is the number of digits afterthe decimal point you want to output. For instance %.3f will output a floating point number with threedigits of precision.

%c Write out a character%s Write out a string of characters

Below are some examples of format strings:

fscanf(fid, '%d %d %f'); Read in two integer values and one floating point value.

fprintf(fid, '%d %.3f\t%s\n', a, b, c)

Write out an integer, a floating point number with three digits ofprecision and a string. Between the integer and floating pointnumber will be a space; between the floating point number and thestring will be a tab. The \n creates a new line in the output file.

fscanf

This function is used to read data from a file. It's format is:

[Mat, Count] = fscanf(fid, format, size)

fid The file handle I talked about above. This is a pointer to the file you want to read data from.

formatThe format string which specifies how the data is organized per row in the file. See the abovedescription.

sizeThis is a more advanced parameter, which is not needed most of the time. You can use this torestrict how fscanf reads in the data. See the Matlab help for more information.

Mat Matrix containing the data read from the file.Count Optional count of the number of data items successfully read from the file.

One thing to note about fscanf is the function is vectorized. This means if your format string specifies how to read in one row of data,

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

5 of 19 1/3/2015 11:08 AM

Page 6: Tutorial #2 - Graphics and Advanced Matlab Features

the output Matrix will contain all rows from the file. fscanf will keep reusing the format string until all values from the file have been readin. This is different from C or C++, where you would need to loop through each row in the file yourself.

There are two major ways you can structure your fprintf functions. You can write out all variables for one row with one function call,or you can write out each variable with one fprintf function call. I personally like the second method to the first, since it makes your codeeasier to read and debug. Remember for every different format character(%d for instance) in your format string you need to have amatching variable as well. If you only have a couple columns in your data file then writing out the entire row with one function call is nottoo bad. However when you have many columns to write out, it can become tedious to match up each format character with itcorresponding variable. Having each format character / variable on a different line makes debugging easier. Either way will work; it just a

matter of what style you want to use. You really need to use the complete format string with the fscanf function, since this function isvectorized.

The next example will create a 4x1 vector and a 4x3 matrix and save them to the same file. The vector has subject numbers and thematrix has their data. The output file will also have a header as the first line.

s = [101; 105; 107; 109]

s =

101 105 107 109

m = [1 12 101.6; 5 7.3 124.87; 3 40 154.8; 7 –1 70.4]

m =

1.0000 12.0000 101.6000 5.0000 7.3000 124.8700 3.0000 40.0000 154.8000 7.0000 -1.0000 70.4000

fp = fopen(‘subdata.dat’, ‘wt’);fprintf(fp, ‘SubNum\tCol1\tCol2\tCol3\n’);fprintf(fp, ‘%d\t%d\t%f\t%.2f\n’, s(1), m(1,1 :3));fprintf(fp, ‘%d\t%d\t%f\t%.2f\n’, s(2), m(2,1 :3));fprintf(fp, ‘%d\t%d\t%f\t%.2f\n’, s(3), m(3,1 :3));fprintf(fp, ‘%d\t%d\t%f\t%.2f\n’, s(4), m(4,1), m(4, 2), m(4,3));fclose(fp);

And here is the output file(subdata.dat) which was written out:

SubNum Col1 Col2 Col3101 1 12.000000 101.60105 5 7.300000 124.87107 3 40.000000 154.80109 7 -1.000000 70.40

In the example above, here is what happened:

I first created a vector and a matrix.

I opened the file as a text file and if another file by that name already exists, it will be overwritten(wt).

I wrote out a header line to the file as the first line. Note there are no variables defined on this line. Since I am only writing out text, Idon’t need to specify any variables or % codes. The \t says to put a tab between each value. If you want a space between the columns, justreplace the \t with a space. Also note the \n at the end of the format string to mark the end of a line.

I then wrote out the four lines of the vector and matrix. Notice the first 3 lines are written out differently then the fourth line. With them(x, 1:3), each column in that matrix row will cycle through the current format string character, in this case .2f. On the last line, I specifiedeach column in the matrix. Also not the .2f, this indicates I only want two decimal places output.

I closed the file.

PlottingMatlab has very extensive plotting capabilities. You have many types of 2D graphs, as well as 3D graphs. You can have a title on a

graph, label each axis, change the font and font size, set up the scale for each axis and have a legend for the graph. You can also havemultiple graphs per page. If you need more customization, you can use what is called handle graphics; this is Matlab’s low level interface toit’s graphics engine.

To illustrate some of Matlab’s plotting functions, I’ve created a file of weather statistics from January 1996. The first line is a headerline. Each row represents a different day. Here is the meaning of each column:

Column Meaning1 Max temp

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

6 of 19 1/3/2015 11:08 AM

Page 7: Tutorial #2 - Graphics and Advanced Matlab Features

2 Min temp3 Mean temp4 % sun5 snow6 snow depth

The file is called weather stats.xls. First, let’s load the sheet into Matlab:

data=xlsread('weather stats.xls');whos

Name Size Bytes Class

data 31x6 1488 double array

Plot functionTo create a linear 2D plot, use the plot function. It’s basic syntax is:

plot(X1, Y1, LineSpec, PropertyName, PropertyValue), where:

X1 X-axis data vectorY1 Y-axis data vectorLineSpec A string value which allows you to specify the line type, color and marker stylePropertyName Handle graphics property name you can set for the graphPropertyValue Value for the above handle graphics property

To plot all columns in a matrix on one graph.

You can see that each column in the data has adifferent color. If Matlab runs out of colors in it’scolor table, it will start back at the first color.

plot(data)

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

7 of 19 1/3/2015 11:08 AM

Page 8: Tutorial #2 - Graphics and Advanced Matlab Features

To plot just the mean temperature(column 3) on agraph

plot(data(:, 3))

To plot only the first 15 days of the minimumtemperature(column 2) and snow depth(column 6) onthe same graph

plot(data(1:15, [2 6]))

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

8 of 19 1/3/2015 11:08 AM

Page 9: Tutorial #2 - Graphics and Advanced Matlab Features

To plot only days 1, 5, 10, 15 and 20 of the minimumtemperature and snow depth on the same graph:

plot(data([1 5 10 15 20], [2 6]))

You can see in the above graph the x-axis does notaccurately reflect the x-axis values. You need tomanually modify the x-axis values. To do this, selectEdit|Axes Properties from the figure window. Uncheck the Labels check box for the x axes. Enterthe numbers 1, 5, 10, 15 and 20 in the edit box. Alsouncheck the Ticks check box and in the edit box atright type [1 2 3 4 5]. You should now have a graphlike the one to the right.. Of course, you can makethese changes in code as well.

Plot line propertiesThe most common line properties you will deal with are marker type, line style, line color and line width. Of those four, only the line

width needs to use a property/value pair; the others can be specified with the lineSpec parameter. There can be up to three parts to a linespecification, line type, marker type and color. The table below lists the three different fields and the symbols for each.

Line Styles Marker Styles ColorsSymbol Style Symbol Marker type Letter Color

- solid line + plus r red-- dashed line o circle g green: dotted line(colon) * asterisk b blue-. dash-dot line . point c cyan x cross m magenta s square y yellow d diamond k black ^ upward triangle w white

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

9 of 19 1/3/2015 11:08 AM

Page 10: Tutorial #2 - Graphics and Advanced Matlab Features

v downward triangle > right triangle < left triangle p pentagram h hexagram

So let’s redo figure 3, this time setting the line stylesfor each of the two columns

plot(1:15, data(1:15, 2), '-r', 1:15, data(1:15, 6), '--ob')

In many cases, you will want a separate graph in a separate window. If you have a figure window open, then issue a plot function for adifferent graph, the new graph will replace the graph in the most current figure window. To insure each graph you create will be in a unique

figure window, precede the plot command with the figure function, like this:

figure, plot(data(:,1))

If you always precede your plot function with a figure function, then you will not have to worry about overwriting another figurewindow. If you want a specific figure window number, type figure(num). So if you type figure(6), a figure window will open with thecaption Figure No. 6.

You may also have times when you have many figure windows open at once. You should close any figure window once you are done

with it, since each open figure window consumes system resources. To close a figure window, type close. This will close the current figure

window. But if you end up having many open figure windows, there is one function which will close all of them; It is close all. This can bea real time and frustration saver!

Graph title and axes labelsThere are three different functions for this. They are:

title(‘text’) Title will be centered at top of graphxlabel(‘text’) Text will be placed along bottom of x-axisylabel(‘text’) Text will be placed along side of y-axis

This is one area where knowing how to concatenate strings becomes very handy. Many times you may want to title your graph with saythe name of the data file it came from.

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

10 of 19 1/3/2015 11:08 AM

Page 11: Tutorial #2 - Graphics and Advanced Matlab Features

Let’s do an example where we illustrate the abovethree functions and string concatenation.

fname = ‘weather stats.xls’; figure, plot(data(:, 6),'--ro')title(['snow depth from file ' fname])xlabel('Days')ylabel('inches')

LegendsYou can place a legend on your graph with the legend function. It’s basic syntax is:

legend(string1, string2, stringN, pos) where:

string1 to stringN Each string would correspond to a different line on your plot

pos

Position on the graph window where you want the legend. If you don’t include thisparameter, 0 is assumed. Values are:

0 = Automatic "best" placement (least conflict with data)1 = Upper right-hand corner (default)2 = Upper left-hand corner3 = Lower left-hand corner4 = Lower right-hand corner-1 = To the right of the plot

Let’s use the plot from figure 6 as an example.

plot(1:15, data(1:15, 2), '-r', 1:15, data(1:15, 6), '--ob')legend(‘Min temp’, ‘Snow depth’, 3)

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

11 of 19 1/3/2015 11:08 AM

Page 12: Tutorial #2 - Graphics and Advanced Matlab Features

While on the subject of text and labels, you can add Greek letters and symbols to your titles and labels. Matlab uses a subset of the TeXcharacter set to do this. The number of special characters is too extensive for me to reproduce here. To see the table of special characters,go into the html Matlab help. On the contents tab, click on the Matlab book icon if it is not open. Click on the handle graphics propertybrowser line. In the right window you will see two vertical scroll bars. Move down on the left one until you see the String property andclick on it. Then move down with the right vertical scroll bar until you see the table of characters. All the special characters need to bepreceded by a backslash character.

So if you wanted to place a number on your graph which represented a temperature, you could use the following TeX character:

title('Temperature is 15\circ')

where the \circ represents the degree symbol.

Changing the scale of axesTo change the x or y-axis scale, use the axis function. It’s basic form is:

axis([xmin xmax ymin ymax])

There is not a separate function for changing just the x or y-axis. If you want to only change one axis while leaving the other alone, youneed to set the other axis values to –Inf and Inf. As an example, we will take figure 8 and change the y-axis values only. Notice thatbrackets need to enclose the numbers, and parenthesis enclose the brackets.

plot(1:15, data(1:15, 2), '-r', 1:15, data(1:15, 6), '--ob')legend(‘Min temp’, ‘Snow depth’)axis([-Inf Inf 5 25])

Hold and subplotWhen you issue the plot function, either a new figure window will be created if one does not already exist, or the most recently opened

figure window’s contents will be overwritten with the new plot. This is why I was saying above that you should always have a figure, plotpair, so that you don’t accidentally overwrite another plot. However there are times when you want to add a plot to an existing graph. Use

the hold function for this. As an example, I’ll create figure 3 using two separate plot functions in conjunction with the hold function.

plot(data(1:15, 2))hold onplot(data(1:15, 6))hold off

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

12 of 19 1/3/2015 11:08 AM

Page 13: Tutorial #2 - Graphics and Advanced Matlab Features

Now let’s create an overlay plot using the holdfunction. I will overlay a line plot and bar graph onthe same window.

figure, plot(data(1:15, 2))hold onbar(data(1:15, 2))hold off

Instead of placing multiple plots on one graph, you also may want to place multiple graphs in one figure window. To do this, you use the

subplot function. The subplot function takes three parameters. To understand the subplot function, think of breaking down the figurewindow into a matrix of separate plots. The first parameter specifies the total number of rows in the matrix. The second parameter specifiesthe total number of columns in the matrix. For all subplots within a figure window, the first two parameters remain fixed. Only the thirdparameter changes, and this indicates the cell within the matrix you want to place the plot into. The cells are numbered with the upper leftbeing 1 and increasing as you move to the right. When you run out of columns for that row, then you move to the left on the next row. Below are three examples to let you get an idea of how this works

figure, subplot(2, 1, 1), plot(data(:, 1))subplot(212), plot(data(:, 2))

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

13 of 19 1/3/2015 11:08 AM

Page 14: Tutorial #2 - Graphics and Advanced Matlab Features

figure, subplot(121), plot(data(:, 1))subplot(1, 2, 2), plot(data(:, 2))

figure, subplot(2, 2, 1), plot(data(:, 1))subplot(222), plot(data(:, 2))subplot(223), plot(data(:, 3))subplot(224), plot(data(:, 4))

Note the two different ways you can specify the numbers within the subplot function. Using commas is easier when writing programs,but at the command line leaving out the commas saves the fingers some wear and tear. Also note that if you want to add legends, titles or

change the current plot in any way, it is easier to do this before issuing the next subplot function. If you do need to go back to a previous

subplot, use the subplot function and use the window number you want to modify.

Aspect ratioBy default, the graphs which are displayed try and fill as much of the figure window as they can. This can cause some distortion in that

both axes may not be the same size. The axis function which I talked about above, has many more options, one of which is setting theaspect ratio of your graph. I will graph a ball with the default aspect ratio and with a square aspect ratio.

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

14 of 19 1/3/2015 11:08 AM

Page 15: Tutorial #2 - Graphics and Advanced Matlab Features

figure, spheretitle(‘Default axes’)

figure, sphereaxis square, title(‘Square axes’)

Changing font attributesChanging font attributes requires using property name/value pairs. This is a simpler method then getting a handle to a text object and

using the set function to change it. There are three major font properties, they are:

FontName Name of the font family you want to use. To find out what fonts are installed on yourcomputer, go to the Start|Settings|control panel and double click on the fonts icon.

FontWeight Can be normal, bold, light or demiFontSize The size of the font

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

15 of 19 1/3/2015 11:08 AM

Page 16: Tutorial #2 - Graphics and Advanced Matlab Features

Let’s take figure 7 and jazz it up some.

fname = ‘weather stats.xls’;figure, plot(data(:, 6), '--ro')title(['snow depth from file ' fname],'FontName','Script','FontSize',36,'FontWeight','bold')xlabel('Days', 'FontName','bookman oldstyle','FontSize',24,'FontWeight','light')ylabel('inches', ‘FontSize’, 16)

Graph typesThere are many different types of graphs you can create in Matlab. Some of the more common are:

plot Basic line and scatter plotsplotyy Like plot, but with y-axis on left and right sidesloglog Plot with logarithmic scale on both axessemilogx Plot with logarithmic scale only on the x-axissemilogy Plot with logarithmic scale only on the y-axisbar Vertical bar graphsbarh Horizontal bar graphsarea Area plotspie Pie chartshist Histogramsstem Stem plotscontour Contour plots

Using the figure windowThere is a lot more a figure window can do then just sit on the screen and look pretty. I’ll go through the major features.

SavingYou can save a graph in a figure window to a .fig file. In the figure window, use File|Save. This is a binary Matlab file which keeps all

the attributes of the graph. To open the figure use the open menu option from the Matlab window. Browse to the .fig file you want to openand a new figure window will be displayed with the graph. This is handy for saving all your graphs for a project, in case you have to go backlater and print out another copy.

Use can use the File|Export menu option from the figure window to export your graph to another file format which can be read intoprograms like Photoshop, Word or Excel. Under the Save as type drop down list box there are a number of file formats for you to choosefrom. The most common are .bmp and .jpg. BMP files are larger then their JPEG counterparts, but they don’t loose any information. JPEGfiles are smaller, but they are smaller in file size at the expense of the loss of information. You may never even notice any difference; theJPEG compression algorithm throws away color differences which we probably wouldn’t notice anyway.

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

16 of 19 1/3/2015 11:08 AM

Page 17: Tutorial #2 - Graphics and Advanced Matlab Features

Changing graph attributesIf you click anywhere on your graph, you may be disappointed to find that nothing happens. A figure window has a plot editing mode

toggle, which is off by default. To turn plot editing mode on, click the upward pointing arrow on the figure window toolbar(the arrow next tothe printer icon). Now if you click in your graph, you can now edit it. To turn off plot editing mode, click on the upward arrow again.

You can add a legend to your graph by selecting Insert|Legend from the figure window menu. If you are in plot editing mode, you canclick on the text within the legend and change it to something more meaningful. To delete the legend, click on the legend so you see theblack handles and then press the delete button. If you want to move the legend to a different position, be sure the legend handles areshowing, then right click and select Unlock axis position. When you see the four arrows you can then move the legend around.

Any titles or labels on your graph you can either move around or edit the text. Click on it once to get the handles to move it around, ordouble-click on the text to change the text.

Double-clicking on the plot area will open the property editor so you can modify attributes like markers, line color or thickness andothers. Double-clicking on any of the axes will open the property editor for the axes. This will allow you to modify the scale, ticks, and fontattributes, among others.

You can also zoom in or out of the graph to see different levels of detail. Click the magnifying glass with the plus sign to zoom in. Draga rectangular marquee around the area you want to zoom in to. Double-click anywhere in the plot to zoom out to x1 magnification. You canclick on the magnifying glass with the minus sign to zoom out.

The dotted circle with the arrow to the right of the zoom out icon will allow you to rotate your graph in 3D space. This is most usefulwith 3D graphs of course.

You can use the Tools|Basic Fitting option to fit a curve to your data using several different methods. If you check the Show equationscheck box, the equation used to fit your data will be displayed on the graph as well.

You can use the Tools:Data Statistics option to display lines on your graph representing various basic statistics. This won’t display theactual numerical values on your graph however. You could take the values from the dialog box and add the numerical values to the legendfor each stat you wanted displayed, although it would be nice if Matlab did this automatically.

Finally, with the A icon(sixth icon from the left) you can add freeform text, arrows or lines to your graph. You can add freeform textwith Matlab code with the text and gtext functions.

Advanced features and good stuff

Internal formatting of dataI’ve mentioned before about the different types of data in Matlab, like scalars, vectors and matrices. I’ve also mentioned there are

different types of data you need to be concerned with if you use a format string with the textread function or the low level functions. I’dlike to talk some about what that actually means. This isn’t critical to your understanding of Matlab, but it may help you to understand whatis going on in the background.

There are four major categories of scalar types, characters, strings, integer numbers and doubles. The unit of storage in a computer isthe byte. The computer you are reading this on may have 128MB of memory, or 128 million individual bytes for storage. The followingtable shows how many bytes each data type takes:

Type Example Bytes of storagecharacter ‘a’, ‘1’ 1 bytestring ‘cat’, ‘file.dat’ Number of characters in the string, plus a few extra bytes for string length

integer 1, 55, 0, -10 Can be 2 or 4 bytes. A four byte integer can hold larger values then a 2 byteinteger.

doubles 1.245, -8 8 bytes

As you can see, there is some overlap. A number can be represented as a string. A string representation of a number can be convertedinto a number. A double can hold an integer number. However, an integer variable can not hold a double number without loss of precision. When you read numbers into Matlab, most times the number are stored as doubles, even if an integer could be used. With the size ofcomputer memory today, this is generally not an issue. I bring it up because it helps you understand how the format characters in a format

string work, in functions like textread. For instance, let’s say you wanted to read in the following line of data(one line.dat) with textread:

male 5 1.56 78

The first column is a string, the second and fourth an integer and the third a double. Now let’s read it in:

[col1, col2, col3, col4]=textread('one line.dat', '%s %d %f %d');col1

col1 =

'male'

[col2 col3 col4]

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

17 of 19 1/3/2015 11:08 AM

Page 18: Tutorial #2 - Graphics and Advanced Matlab Features

ans =

5.0000 1.5600 78.0000

whos

Name Size Bytes Class

col1 1x1 100 cell array col2 1x1 8 double array col3 1x1 8 double array col4 1x1 8 double array

Notice even though we used %d to read in an integer value, it still came in as a double. This does waste some memory, but usually isn’ta problem. Column 1 was read in as a cell array, which I’ll talk about in another section. For the moment, just think of a cell array as astring. Now let’s try reading in the third column as an integer:

[col1, col2, col3, col4]=textread('one line.dat', '%s %d %d %d');?? Trouble reading integer from file (row 1, field 4) ==> .56 78\nError in ==> D:\Programs\MATLAB6p1\toolbox\matlab\iofun\dataread.dllError in ==> D:\Programs\MATLAB6p1\toolbox\matlab\iofun\textread.mOn line 169 ==> [varargout{1:nlhs}]=dataread('file',varargin{:});

Matlab was smart enough to realize the number in the third column did not match the format specifier. In most programming languages,the above mistake would have read the number in as 1, not 1.56.

Now let’s try one more example. Let’s read in all the numbers as doubles::

[col1, col2, col3, col4]=textread('one line.dat', '%s %f %f %f');[col2 col3 col4]

ans =

5.0000 1.5600 78.0000

The numbers did read in fine, so you can read in integer numbers with the %f format specifier.

There is also a duality between characters and integers. Every character has an integer number associated with it; these are calledASCII codes. For instance, A equals ascii code 65. Use the double function to convert a string to it’s ascii equivalent. Use the charfunction to convert an ascii code to it’s character equivalent.

This whole discussion has been to give you an understanding of the importance of choosing the right format specifier in your formatstrings. If you understand this section, then you shouldn’t have much trouble with format strings.

StructuresYou can think of structures as an enhanced matrix. While a matrix has columns, a structure has fields. Each field has a name associated

with it that you assign. All columns in a matrix must hold the same type of data. Each field in a structure can hold a different type of data. With structures you can build a data hierarchy, that is you can have structures within structures. For basic data analysis with twodimensional datasets, structures are generally overkill. However depending on what you are trying to do, using a structure can be easier thenusing multiple vectors or matrices to hold the data. Where could you use structures in your use? Let’s say you have several files you wantto load into Matlab at one time. Each file has a different sample rate and test condition which you want to store with the data. I’m going todirectly assign values to the structures, but in a real program you would load the values from files. The structure vector will be called files.

files(1).SR = 100;files(1).Cond = ‘vision’;files(1).Data = [1.25 8.7 3.2; 9.4 1.02 3.4; 7.65 –6.21 0.15];files(2).SR = 200;files(2).Cond = ‘no vision’;files(2).Data = [0.3 7.01 1.9; 4.1 6.7 2.6; 2.1 8.4 7.3];files(1)

ans =

SR: 100 Cond: 'vision' Data: [3x3 double] Data: [3x3 double]

files(2).Data(1,3)

ans =

1.9000

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

18 of 19 1/3/2015 11:08 AM

Page 19: Tutorial #2 - Graphics and Advanced Matlab Features

Cell arraysCell arrays are a step above structures. You can think of a cell array as a container which can hold anything. Cell arrays are accessed

like matrices, with the row, column number notation to access a certain element. However each element can hold scalars, vectors, matricesor structures. Again, for basic two dimensional datasets, cell array are really overkill in my opinion. One area where cell arrays are useful iswhen dealing with string data. I’ve mentioned that the one disadvantage with an array of strings is each string in the array must have thesame length, so shorter strings will have blanks added to the end. With a cell array, each string can be a different length. Another use withcell arrays of strings is on Matlab plots. If you use a cell array with the text function, you can have multi-line labels with one textcommand. Let's show this with an example:

fname = ‘weather stats.xls’;figure, plot(data(:, 6), '--ro')title(['snow depth from file ' fname])xlabel('Days')ylabel('inches')label(1) = {'Heavy'};label(2) = {'snowfall'};text(15, 21, label)

Notice the curly braces around the strings. They are required for cell arrays.

Notice in the examples in parts one and two of the tutorials I’ve not used the program editor to write any programs yet. This illustratesone of Matlab’s strengths, the ability to test and try out different functions right from the command prompt. This is why I always tell peoplewhen they are looking at programs and don’t understand what a function does, type it at the command prompt and see for yourself. Byreading the online help and typing commands at the command prompt, there is no better way to learn Matlab.

Tutorial #2 - Graphics and advanced Matlab features http://www.personal.psu.edu/staff/f/0/f0o/matlab/tutorial2.htm

19 of 19 1/3/2015 11:08 AM