A MATLAB TUTORIAL

by John Stankiewicz

 

TABLE OF CONTENTS

I.        INTRODUCTION.... 3

II.        ORIENTATION....... 3

A.    Starting Matlab..... 3

B.        Looking Around. 3

III.       THE COMMAND WINDOW.. 4

A.    Starting Out  4

B.        Variables     4

C.    Editing matrices... 5

D.    Calling functions.. 6

E.     List of helpful functions and a summary of what they do    6

IV.            GRAPHICS   6

A.    Starting out   6

B.        Toolbars and uses7

C.    Camera Toolbars.. 7

D.    Calling toolbar functions from the Command Window.. 8

E.     A Slightly More Complicated Graph...... 8

F.        Meeting the Requirements of a Good Graph.... 10

G.    List of helpful Command window functions for graphing and what they do        11

V.    M-FILES        12

A.    What is an M-file?12

B.     Writing your own M-file.... 12

C.    Calling your M-files        14

D.        Explanation of the M-files I made..... 14

 


DETAILED TABLE OF CONTENTS

I.        INTRODUCTION.... 3

II.        ORIENTATION....... 3

A.    Starting Matlab..... 3

B.        Looking Around. 3

III.       THE COMMAND WINDOW.. 4

A.    Starting Out  4

B.        Variables     4

C.    Editing matrices... 5

i. TRANSPOSE.... 5

ii. CHANGING ONE ENTRY WITHOUT THE ARRAY EDITOR5

D.    Calling functions.. 6

E.     List of helpful functions and a summary of what they do    6

IV.            GRAPHICS   6

A.    Starting out   6

B.        Toolbars and uses7

C.    Camera Toolbars.. 7

D.    Calling toolbar functions from the Command Window.. 8

E.     A Slightly More Complicated Graph...... 8

F.        Meeting the Requirements of a Good Graph.... 10

G.    List of helpful Command window functions for graphing and what they do        11

V.    M-FILES        12

A.    What is an M-file?12

B.     Writing your own M-file.... 12

C.    Calling your M-files        14

D.        Explanation of the M-files I made..... 14


 

I.                  INTRODUCTION

 

Welcome to the Matlab tutorial!  In this manuscript I plan to go over all of the features that you will need in order to become a pro at graphing in Matlab.  Along the way I’ll cover everything from basic techniques to m-file programming.  If you ever get lost or confused, I recommend using the book that helped me Mastering Matlab 6.  If that doesn’t work, Matlab offers an extensive (if not so helpful) help-menu.

 

 

II.               ORIENTATION

 

A.   Starting Matlab

To begin using Matlab, you should probably start the program.  You can do this            in a number of different ways, but probably the easiest is to:

 

·        Find shere khan or baloo.  Currently these are the only 2 computers in the lab that are Matlab equipped.  

·        Next, log in using your Schumacher account.

·        Go to the start button in the lower left corner of the screen.

·        Go to programs.

·        Go to Matlab Release 12 and click on Matlab R12

 

Congratulations!  Now, that wasn’t so scary was it?

   

B.   Looking Around   

Now that you’ve successfully started Matlab it’s time to familiarize yourself with your surroundings.  Go ahead and maximize that Matlab window, that way I know we’ll be on the same page as far as displays are concerned.  Alright, now what you should be looking at is a window that looks as if it’s composed of three separate windows, two on the left side and one on the right side.

       The top window on the left hand side has tabs that appear on the bottom that you can toggle through. These tabs are Launch Pad and Workspace.  Please toggle the Launch Pad tab now. 

         What you will now see is the Launch Pad window.  This is a function of Matlab that I have not used very often.  Most of the features of this window can be easily accessed via the Command Window (which we will discuss in a moment).  Anyway, by clicking on the MATLAB icon you can open the help window, the demos window, your current workspace, path, GUI (graphical user interface) builder, and the product web-page all from right here.  Take a second and look at some of the demos if you want. (just double click on the light-bulb icon.)

          Now go ahead and toggle to the Workspace tab in that same window.  The workspace window is helpful in that it easily shows you the names, size, and class of all of the variables that you have created so far in Matlab.  Right now it should be empty, but as we continue to work, you’ll see it start to fill up with your very own variables.

          The window that appears on the bottom left hand side of the screen also has tabs that appear on the bottom.  The tabs here are the Command History and Current Directory windows.  Let’s toggle into the Command History window now.

           The Command History window tells you the history of every command that you’ve used in the past month (Matlab can tell what day it is, just type “date”).  This is very useful.  It will help show you exactly where you left off with your last session. 

            Now let’s toggle over to Current Directory.  This window shows you all of the files that you’ve used in Matlab over the past month (or maybe a little longer, I’m not really sure).  You can find all of the M-files that you’ve created here, plus all of the data files that you’ve input, etc.  I haven’t really used this window very much.

            The window that appears on the right hand side is the Command Window (in fact it’s even labeled if you look close enough.)   This is the main control for Matlab.  If Matlab were a spaceship, the Command Window would be the bridge. If Matlab were a small, Central American, Banana Republic the Command Window would be the ruthless dictator, if Matlab…….anyway, you get the idea.  

           We’ll be discussing the Command Window a lot in the next section.

 

 

III.           THE COMMAND WINDOW

A.   Starting Out

Alright, now it’s time to get busy.  In the window on the right hand side you aught to see a line of text “To get started, select "MATLAB Help" from the Help menu” and then you should see two arrows “>>.”  Those little arrows are the line prompt.  This is where you will be creating variables, entering commands etc. Matlab works with matrices and arrays.  This means that every variable that you create will simply be a collection of discrete points.  To better see what I’m talking about, let’s create a variable called “x”. 

B.   Variables

The very first thing you should do is to click the pointer onto the command prompt.  Next simply type          x  = [ 0 1 2 3 ]   and press ENTER.  What this says to Matlab is that you are creating a variable x.  x is an array with 4 values.  The values are 0,1,2, and 3.  You can also make x a matrix.  By typing x = [0 1 2 3; 4 5 6 7]  you have just made x a 2 by 4 matrix ( row 1 column 1 = 0,   row 1 column 2  = 1, etc.)  Matlab has automatically overwritten the original array that we had stored in x with the new matrix version.  Note that if the number of columns in the first row does not match the number of columns in the second row Matlab will give you an error message.  You can look at the variables that you have created by clicking on their icons in the workspace window.  This will bring up the array editor window and you will be able to look at your variables in a spread sheet fashion (up to a certain size).  You should also see a display of the variable in the Command Window.   Sometimes however you don’t want to see the entire variable displayed.  Whenever you don’t want Matlab to display the results of an instruction entered on the command line all you have to do is to type “ ; “ after the command  ( i.e. x = [0 1 2 3; 4 5 6 7];  would still create the variable, just not display it to the screen).  There are several other variable types that can be created, we simply covered arrays and matrices here.  You can also store text ( x = ‘ecks’).       There are many more convenient ways of constructing your arrays using functions, especially if you need linear ones.  I’ve compiled a complete list of commands that I’ve found useful at the end of this section, but first, let’s get the hang of editing our matrices.

C.   Editing matrices

Ok, now that we’ve created a matrix ( x = [ 0 1 2 3; 4 5 6 7] from above), let’s learn how to manipulate it.  Possibly the easiest way if you have a small matrix is to use the array editor.  To open the array editor simply right click and choose “open selection.” You can change the entries in your matrix simply by clicking on the right row and column number and changing the entry, just like a spreadsheet.  Let’s go ahead and open the array editor and change the entry in the second row and third column to the number 8.  To see how your variable has changed you can either look at it in the array editor or by typing “ x “ in the command window.                 This is fine to do if you only want to change one or two entries, but what if you want to make large scale changes?   There are several techniques  that you can use to change whole rows, or columns, or even concatenate two matrices together. 

i. TRANSPOSE.

A transpose takes a matrix and flips it.  The first row of matrix A becomes the first column of matrix A’.     To do a transpose all you have to do is to type  x’ in the Command Window (I’m going to start abbreviating Command Window to C.W.) . When you type this Matlab responds with                                                                    ans =                                                                                                   0    4                                                                                                    1    5                                                                                                           2    8                                                                                                       3    7                                        now the variable “ans” is equal to the value of x’.  “ans” is the default variable that Matlab uses if you don’t assign a variable name.

ii.  CHANGING ONE ENTRY WITHOUT THE ARRAY EDITOR

            You can also change individual entries without the array editor if you know the row and column numbers of the element that you’d like to change.  You simply have to type the variable’s name followed by the row and column number of the entry to be changed and set that equal to the new value.   Here’s an example:      x(1,3) =  4        changes the variable x   to    [ 0 1 4 3; 4 5 8 7]   If you specify a row or column number that doesn’t exist in that particular matrix  Matlab will automatically expand your matrix to fit 

                        i.             CHANGING WHOLE ROWS OR COLUMNS:   You can change whole rows and columns by using the colon operator (no not the proctologist)  “ : “       There’s a whole section in the Matlab help menu that covers the colon operator, but I’ll only cover a small part of that here.      First I’ll give an example and then explain what’s going on.        To set all of the values in the second row of ‘ x ‘ equal to the number 2.  Simply enter                x(2, :) = 2              the result is that    x  = [0 1 4 3; 2 2 2 2]      you can also make the second row disappear  by setting it equal to a null set.     x(2, :) = []       will yield   x = [0 1 4 3]        This same technique can be applied to columns.    To change the value of every entry in the third column of x to 10 simply type x(:, 3) = 10   If you’d like to be more specific you can do that too.   Suppose you had a 10 by 10 matrix called “tens” and you wanted to change the values of the 7th column from row 3 to row 9  to the number 42.   All that you would have to do would be to type  tens( 3:9, 7) = 42.        The same method will work for columns also.  The colon operator is essentially a way of saying “go from a to b in integer increments”    or when used on it’s own it’s a way of saying “ every row or column”

                      ii.            CONCATENATION:      Suppose that you have two matrices that you would like to have combined (that is to say stacked onto one another).    Let’s create two matrices.   Type                                   building = [1:10; 11:20]           and        block = [1:9; 10:18]    You should now have two matrices to work with, building is 2 by 10, and block is 2 by 9.   Now you can try concatenating them.  Try    B = [building block]          this will simply concatenate the two matrices side by side.  Now try B = [building; block].   This last command should produce an error message because the two matrices do not have the same number of columns.   If we add an additional column to “block” then we should be able to concatenate the two matrices.   I suggest typing                   block(:, 10) = 2   and then B = [building; block]       or                  B = [block; building] 

                     iii.            ELEMENT BY ELEMENT MATHEMATICAL OPERATONS ON MATRICES:    Matlab works  entirely in vectors and matrices, but sometimes you don’t want it to.  For instance, let’s say that you had the variable Y = [ 0 1 2; 3 4 5; 6 7 8]       and you wanted to multiply every entry in Y by 2.  You could type Y * 2,  2 * Y, or Y .* 2.   The important command is the last one.  This command does element by element multiplication.  Likewise  ./ does element by elem.  Division, and .^ does elem. by elem.  powering.       

D.   Calling functions  

  Functions are matlab’s tools.  In mathematics people think of functions as f(x), something acting on x to create a new output.  In Matlab that’s not always the way it works.  I’ll explain.  Here in Matlab you can use functions to generate variables.  For one example we will use the “linspace” function.  This is a function that takes either two or three inputs from the user and uses those inputs to create a vector with linear spacing between entries.  If that isn’t straightforward enough, let’s go ahead and enter it into Matlab.   At the command prompt type        x = linspace(1,10)         What this is doing is saying that a new variable x is equal to what the linspace function gives for input variables 1 and 10.  Linspace creates a variable that’s first entry starts at 1 and linearly increases entry by entry up to 10.  Without a third input Linspace’s default is to create 100 entries.  You can change this simply by adding a third input    x = linspace(1,10,10)  gives x equal to [1 2 3 4 5 6 7 8 9 10].    There are many other functions that are useful (the entire graphics package consists of functions).  All of the ones that are pertinent for variable creation are listed at the end of this section. (those that are appropriate for graphics creation are listed at the end of that section).   You can also write your own functions using the M-file editor, but we’ll discuss that more later.

E.   List of helpful functions and a summary of what they do

      A list of helpful functions

                                                               iv.    x = linspace(a,b,c)       covered above

                                                                 v.    More on the colon operator.  The colon operator can also be used as a way of creating linear arrays.  You can use it to make an array like x = [1 2 3 4 5]     by entering x = [1:1:5]    or in other words x is equal to the set of numbers that starts at 1 and steps linearly up to 5 in steps of 1.   Likewise an array could be made like x = [1 3 5]   by entering x = [1:2:5]    or an array like                   x = [5 4 3 2 1] could be made by entering x = [5:-1:1]    You will be using this command all of the time.  Many parts of Matlab require there to be a mesh in order to graph 3D objects, this is the command you will use.

 

IV.           GRAPHICS

A.   Starting out

1.  Ok, time to start graphing.  Let’s make a simple matrix.                          X = [ 0 0 0 0 0;  0 1 1 1 0; 0 1 2 1 0; 0 1 1 1 0; 0 0 0 0 0]   (feel free to cut and paste!)           OK, now we’re going to pretend that this is one of  your data sets.  Let’s graph it.   You graph variables using a variety of different functions.  Here’s a short list    mesh(X), surf(X), contour(X),    for the purposes of this demonstration it’d probably be best if you chose to     mesh(X).      Ok, so what will happen next will be that a figure window will pop up.  Yeah, I know it looks pretty bad, but it’s just an example.    Alright, so let’s take a look at that graph.  You should be able to see right off the bat that what the graphics program is doing is labeling the axis with row and column numbers (rows are the x-axis, columns the y)  It then takes the values of the entries and graphs that value at the intersection of it’s row and column number (i.e.  the value 2 is placed at the intersection of 3 on the x-axis and 3 on the y-axis and has a z-axis height of 2).   The next thing that you might notice is that this is a “wire-frame” image of the data, this is because it is a mesh graph of the data, a surface graph would look slightly different.  The next thing that you should notice is the coloring.  Matlab uses color as an additional height indicator.  Here red is high and blue is low.  You can change the color settings in several different ways, but we’ll talk more about this later.

 

B.   Toolbars and uses

2.  Now that we’ve graphed an object, let’s talk about the different toolbars that are available.  There is a toolbar at the top of the image with little icons on it (like a blank sheet of paper, a folder, a disk, etc.).   The first four icons are pretty self explanatory.  The next 4 are a plot editor, a text, arrow, and line inserter.  The last three icons are zoom in, zoom out, and rotate.   Let’s use the rotate icon to take a look around our graph.  Click on the rotate icon and then click and drag on the graph to move it around.  You can look at the figure from any angle.  You can also zoom in or out by clicking on the appropriate action and then clicking on the object.  You can also insert text or arrows, lines, etc. using the other icons.  I don’t really use those functions very often.  Ok, now that you’ve gotten used to those controls let’s open up the camera toolbar. 

C.   Camera Toolbars

3.  The Camera Toolbar lets you control the view of the scene as though you were looking at the image through a camera.  It has features that let you control almost every aspect of the camera.  You can open the camera toolbar by going to the top of the figure window, and clicking on view and then checking on the Camera Toolbar box.  This opens up a whole new toolbar of fun stuff.  The first icon I don’t really use all that often because as far as I can tell it does the same thing that the rotate image icon does in the figure toolbar (discussed in part IV section 2).                                               The next icon is for orbiting the scene light.  This is only used for surface graphs with shading.  Again, this is not used very often. What it would do would be to change the apparent angle that the light was shining on the object from (like moving the sun in the sky.)                                                                                                   The next icon is the Pan/Tilt one. It pans or tilts the camera.  Not really useful.                                                                                        The next icon is for Moving Horizontally and Vertically.  This is useful for positioning the image anywhere that you want on the screen.  It also affects the rest of the commands.  Try orbiting the scene camera after moving the image off to the side of the screen.  You’ll see that it still orbits the camera around whichever axis is chosen, just not centered on the image anymore.             The next icon is for Moving Forward and Backward.  This is essentially a zooming command.  You can use this by clicking and dragging on the image.                                                                     The next icon allows the user to roll the camera.  You can get the same effect by rotating the image with the earlier icons, but maybe there are some situations where this would be easier.                      The last of the image movement commands is the camera walk command.  To use this you should imagine that there is a person holding the camera and you are telling that person which direction to walk using the mouse pointer.  I found that this command was more than useless; it was often confusing.  Perhaps it is useful in some movie making contexts, but I never found a good use for it.    That does it for the image movement icons, the next set of icons are the axis icons.  These simply specify which axis the image movement commands are performed about.  Take image rotation for example, it’s default axis is the z-axis, however using the axis icons you can change the axis of rotation to the x or y axis.  Not really helpful.                                                                                                 The next icon is the lightbulb icon.  When you are graphing objects that depend on lighting (like some surface graphs) you may need to be able to change the orientation of that lighting.  Clicking on the lightbulb icon is an easy way to do this.  Simply click and drag until you have the lighting that you want.  The lighting command is useful for those surface graphs with colormaps that involve different shades of one color, and not with colormaps with a wide variety of colors (like hsv, jet, ect.), therefore it hasn’t been useful in the graphs that I’ve been using.                                                                    Then next two commands change the projection from orthographic to perspective.  I don’t really know what this does.  It seems to affect the angles at which the axis intersect, but I don’t know why this would be useful.                                                                                The icon is probably the most important of the set. This is the reset button.  You can use this to reset the figure to it’s original settings.  This is very useful.                                                                               The final icon is the stop button.  Sometimes you’ll find that with large, complex images it simply takes too long to do whatever commands you’re asking Matlab to do.  If you decide that it’s no longer worth the wait you can tell Matlab to stop with this icon.

D.   Calling toolbar functions from the Command Window

4.  Command Line camera commands.  Some useful commands can be found in by looking up camera commands in the help menu.  The most useful ones are                  camview                  camtarget                  camva                   

E.   A Slightly More Complicated Graph

5.  Now that we’ve covered all of the basics of learning to look at your figures, let’s make a more complicated graph and start refining our techniques.                                      First I’d like to tell you the mental picture that I’ve drawn up about making 3-D graphs.   The data that you are trying to graph must always be presented in matrix form.  I imagine stretching this data down onto a grid that is made up of my x and y axis.  The size of your matrix and the grid must be the same in order to get a good match.                         The graph that we did earlier was simple in the fact that we constructed it row by row.  We didn’t have any x or y values to worry about, we simply graphed it.  When we expect to graph functions that are dependent on x’s and y’s it’s a little different.   The first part of making a 3-D graph is to lay down the grid which the data will be plotted against.  Let’s do an example:                Let’s say that we want a grid that has x going from –7.5 to 7.5  and also y ranging from –7.5 to 7.5, and also let’s have them both step through those values in steps of .5 (remember, Matlab likes to work in arrays and matrices, therefore we can’t just leave x and y to be continuous. They must be broken up into a discrete set of points).     What we will do is to use a command called meshgrid.  We should type  [x y] = meshgrid(-7.5:.5:7.5, -7.5:.5:7.5);     What this command does is to make matrices out of the variables x and y.  The x variable varies with column, the y variable varies with row.  This way you can set out a complete coordinate system that covers every combination of x and y.                  So, now you’ve made the grid.  How about some data to fit over that grid.  The important thing to remember is that the data must have the same number of rows and columns as the grid that you’re graphing it onto.  Let’s do an example.            We already have values for x and y.  Let’s use these to construct another variable called r.  We’ll make r = sqrt(x.^2 + y.^2) + eps         What this does is to create a variable r that is equal to the square root of the sum of the element by element squared values (notice the “.” in front of the carrot symbol) of x and y    plus the smallest nonzero number allowed on Matlab (eps).    Go ahead and graph this bye using the mesh function.  (simply type mesh(r) ).    And we’ll finish by making the “Mexican Hat”  all we have to do is to type z = sin(r) ./r     and then mesh(z)  will produce the Mexican Hat.                       Note that the graph that is shown automatically labels the x and y axis as the number of the rows and columns in z.  The values should range from 0 to 40 along both x and y.   Well, this is OK, but what we really wanted to see was that x and y ranged from –7.5 to 7.5.   The way that we get the figure to look like this is to graph all three variables at the same time.  Simply type mesh(x,y,z) to see the relevant x and y labels.                   So far we’ve been using the mesh command to create 3-D figures (i.e. mesh(x,y,z) mesh(z), etc.).   There are several more functions you can use to create 3-D graphs.  Most of them are just as easy to use as the mesh function.  You can use surf (it makes the graph into a surface instead of just a wire mesh) , contour (it translates the graph into a map much like a topological map of the earth’s surface), surfc (a surface graph with contour lines underneath.     There are lots of special features that you can use with surface maps that you can’t do with mesh graphs.  One of those features is shading.  You can look up more about the shading methods in the Matlab help menu.  The only one that I’ve found helpful is the interpolative shading    surf(z); shading interp .  You can also create graphs that depend on lighting.  At the command prompt enter   surf(x,y,z,’FaceColor’,’red’,’EdgeColor’,’none’); camlight left; lighting phong                                                                 This tells Matlab to graph x,y,z as a surface, color the panels red, give the mesh no color, put the light in the left corner as seen by the camera and let the graph interpret the shading using phong (there are different ways of interpreting the lighting like gouraud and flat, but they don’t look half as nice.)                  

F.    Meeting the Requirements of a Good Graph

Now we’re going to get into the criteria that Dr. Schumacher says are important for making publication quality graphs.  For organization’s sake I’ll list the qualities first and then you can page through them at your leisure.

                                                                   i.  Making the lines smooth (less pixelization)

                                                                 ii.  Changing the ranges of axis

                                                                iii.  Changing the range of the color axis

                                                               iv.  Labeling and titling axis

                                                                 v.  Orienting text objects at angles to axis

 

 

Making smooth lines.   You may have noticed that the lines on the figure window do not necessarily look very much like straight lines.  Rather they look more a series of verticle and horizontal lines (imagine a diagonal line in an early game of pong).  Well, there’s a way to fix this.  Simply type  set(gcf,'Renderer','painters')            what this does is it gets the current figure’s Renderer property and sets it to painters (instead of “OpenGL” another kind of renderer.)                                                  Changing the range of the axis.  If you’d like to see the figure that you graphed on a different range you can change the axis limits by typing axis([xmin xmax ymin ymax zmin zmax cmin cmax])  where cmin and cmax will be explained in part iii.  This changing of the axis does not make your dataset any larger.  Try expanding the axis on our Mexican Hat.  Type in axis([-20 20 –20 20 –2 2])   You will see that the axis have expanded, but the figure did not grow to fit them.  This is because you are still graphing the original z matrix.  That z matrix is only defined for the ranges of x and y from –7.5 to 7.5     If you’d like to see the z figure actually graphed from x and y from –20 to 20 you have to do that at the initial grid laying with the meshgrid command.                      Changing the color axis.  We’ve already seen that Matlab assigns color to a 3-D map as a way of illustrating z-axis values.  In our Mexican hat example we saw that the colors went from blue at the lower end of the z-values, up to red at the higher end of the z-values.  You have a limited number of colors that you have to stretch over the entire z-axis range of your graph so you must choose a starting point and an ending point to scale your colors over.  An example is that in our Mexican hat figure, Matlab has automatically chosen z = -0.2172  to be the z-minimum color value and  z = 1 to be the z-maximum color value.  You can see which values Matlab has selected by simply typing      caxis      at the command prompt.    If you wish to change the starting and stopping points for color assignment all you have to do is to type        caxis([zmin  zmax])     on the command prompt.   All z values below the zmin will be assigned the lowest possible color setting, and all values above zmax will be assigned the highest possible color setting.   Let’s try this with our Mexican hat.   First, replot with default settings, using surf(x,y,z)  Set         caxis([.2 .5])       Now we’ve squeezed the entire colormap into that space that is between .2 and .5.   I used a new word there “colormap.”   A colormap is like a pallet for your graph.   A colormap contains a fixed set of colors.  The default colormap that we have been using is “jet” it contains colors ranging from blue at the zmin going up through green, yellow, and orange up to red at the zmax.  There are many other maps to choose from (simply type colormap at the help menu), some contain many shades of a single color like “pink”  and some colormaps contain more base colors like “hsv”   To change colormaps simply type       colormap  pink          or                 colormap hsv             or            colormap  jet                                                Labeling and Titling axis.   Now that we’ve got our graph, let’s assign it a title and label the axis.  You do this by assigning graphics properties called   Title, Xlabel, Ylabel, and ZtickLabel.  You can think of these properties as functions with parameters that you can change.  I think that examples often help, so here’s a good one.     title('MEXICAN HAT','Color','black','FontSize',16)

>> XLabel('X-axis','Color','blue','FontSize',14)

>> YLabel('Y-axis','Color','green','FontSize',12)

>> ZLabel('Z-axis','Color','red','FontSize',20)           This is assuming that you still have the Mexican hat graphed in Figure number one.      title assigns a title to your graph.  Inside of the title command we have several different parameters, all you have to do is to say what parameters it is that you’d like to change (Matlab has defaults built in for everything that you don’t want to change).  For instance for title we started off by writing in the title in single quotes.  Next we specified that we’d like to change the ‘Color’ parameter (again in single quotes) to ‘blue’ (even more single quotes), and ‘Fontsize’ to 14.  We don’t need quotes around 14 because it is a number and not a piece of text.  We do the same thing with the Xlabel, Ylabel, and Zlabel commands.  Color and Fontsize are just two properties of text objects.  For a full list see MATLAB Function Reference: Text Properties. 

Now we’re going to go into a little more detail on another one of the text properties called Rotation.   Dr. Schumacher said that one of the things that he would like to see would be to be able to orient text at an angle to the axis.  The way to do this is to edit the rotation property of whatever text you’re editing.  Let’s make an example where you would like to label the x-axis “X-AXIS”  and orient it at a 45 degree angle downward from the x-axis in the x-y plane.  There are two ways to do this, the first way is relatively straightforward because we’ve just used it to add titles to our graph.  Here’s an example                                                                          XLabel('X-AXIS','Color','blue','FontSize',14,'Rotation',-30)                 This will set the xaxis label to “X-AXIS”  in a blue color, with the font size of 14 with a value of -30 rotation in degrees (positive angles cause counterclockwise rotation).  Ok, so now you’re probably asking me “ok, -30 degrees rotation from what.”  It’s always oriented at –30 degrees to the figure.   No matter what orientation you’ve got the figure in, that text will always be oriented at  -30 degrees to it.  (try it and see).                                            There’s another way to do this.  You can put text anywhere on the graph using the text location property.  You can type               text(0,-10,-.5,'X-axis','Rotation',-45);          and this will locate a piece of text (‘X-axis’) at the location (0,-10,-.5)  with a rotation of –45 degrees to the figure.  You can do this for every axis if you want.  This method will take longer than the method already suggested, but it’s also a good way of interjecting text onto your figure for other purposes (it would be a good way of pointing out interesting graph features.)  

G.  List of helpful Command window functions for graphing and what they do

6.  List of Helpful Graphing Commands:            1. mesh(z);   graphs a 3-D wireframe of your data set.  z must be a matrix in order for this command to work.                    2.mesh(x,y,z);  graphs a 3-D wireframe of your data set ‘z.’  Also graphs the matrices x and y along the axis.  X and y must be matrices of the same size as z in order for this command to work.     3.surf(z);  graphs a 3-D surface onto the wireframe of your data.  Similar in function to mesh(z);              4.surf(x,y,z); similar to surf and mesh(x,y,z)          5.surfc(z);  graphs a                 6.Xlabel(‘parameters’); is a function that allows you to label, rotate, change the size of, and otherwise manipulate the x-axis.      7.Ylabel(‘parameters’); see Xlabel            8.Zlabel(‘parameters’); see Xlabel            9.text(‘parameters’); is a function that allows for the insertion of text into your graphs.  The parameters allow you to manipulate the appearance of the text object.

 

V.              M-FILES

A.   What is an M-file?

What are M-files.  

M-files are simply text files that when written a certain way, can be used as programs in your Matlab environment.  They can be written in any ASCII text editor, like Notepad or Word on a Windows machine, or any kind of text editor on a Linux machine.  The commands that you have been calling, such as meshdata and Ylabel, are all M-files.  Now you will be able to write specialized files that do exactly what you want.

B.   Writing your own M-file.

There are several parts to an M-file.  Let’s examine an example file and break it into it’s constituent parts.

 

 

 

function f = loedmesh(h)

%LODEMESH      

%this is a function specifically meant to load data into a matrix

%Ok, originally the idea was to take Ken's data and to put it into

%a matrix with three columns x,y,and z.  Ken's data was originally set up for

%2-D display.  He had 221 data files that gave y values for evenly spaced x-values.

%In order to make this a 3-D display I assigned a new dimmension to Ken's data.  This

%new dimmension is labeled the y-axis (and the old 2-D y-axis is now the 3-D z-axis).

%Ok, so after all was said and done this created a matrix that was 1.5 million rows long

%(7,500 x-points with * 221 y-values) and 3 columns wide, leading to 4.5 million numbers in

%that matrix.  No good.  So I had this idea that I would instead make a matrix that was

%221 rows long by 7,500 columns wide.  This way all the data is laid out row by row like a

%carpet.  This drastically saved space.  Instead of having 4.5 million numbers, now there

%are only 7,500 * 221 numbers or approx 1.5 million.  Here is a graphic representation of what I'm talking about

%

%  before    x    y    z                            now

%

%            1    1    28                                  28   32.2  24  33 ..            27

%            2    1    32.2                                27   28    34  17.8 ..          23.2

%            3    1    24                                  23.3 45    42  ..               23.9

%            4    1    33                                  44   33.3  ..              

%            ..   ..   ..

%          7,500  1    27

%            1    2    28

%            2    2    34

%            3    2    17.8

%            ..   ..   ..

%          7,500  2    23.2

%            1    3    23.3

%            2    3    45

%            3    3    42

%            ..   ..   ..

%          7,500  3    23.9

%            1    4    44

%            2    4    33.3

%           

%           you get the idea

%                               h is simply the number of datafiles to be loaded

 

 

pwd  % this tells  you where you currently are.  You need to be cd'd into the same %directory as the files to be loaded.

B = [1:7313];   % later we're going to need a matrix to concatenate to.  We must first %designate this matrix. That's B.

B(:,:) = 0;     % B has 7313 columns that are all equal to 0.

for i=h:-1:100

    fname = sprintf('fftsp.%.0f',i);     %from i = 100 to i = h it'll do the same stuff

    A = load(fname);

    A(:,1:1) = [];

    C = A';

    B = [B; C];

end

for i=99:-1:10                 

    fname = sprintf('fftsp.0%.0f',i);     %same stuff

    A = load(fname);

    A(:,1:1) = [];

    C = A';

    B = [B; C];

end

for i=9:-1:1       % setting up a counter      

    fname = sprintf('fftsp.00%.0f',i);    %a varble. fname is equal to the string 'fftsp.00counteri'

    A = load(fname);                      %a varble A is equal to the datafile with the name %fftsp.00counteri

    A(:,1:1) = [];                        %the first column of A is erased (getting rid of the x-cord)

    C = A';                               %a varble C is equal to the transpose of A (this flips it into %the orientation we want

    B = [B; C];                           %B is equal to B plus the matrix is expanded to include all %the points in C

end

f = B;                                   %at the end it returns the matrix B that has been built up h %times

return                                   %there'll be 7,313 columns and h rows 

 

Ok, the 1st part of the program is the designator:  function f = loedmesh(h)   this defines that the text that you are writing is a function and that function is called loedmesh .   It also says that there will be one input variable “h” to be used later on in the program. 

 

The next part of the program is the name of the function in all caps  LOEDMESH, this will help Matlab to look for help on this function when you type help loedmesh on the command line in the command window.

 

After the program name comes the help text.  Every line should start with a % sign.  This tells Matlab that whatever follows on that line will be a comment.  (Due to space constrictions here in Word, some of the lines don’t start with ‘%’s but you can probably figure it out anyway.)

 

Next comes the body of the program.  Here the program is a loading program that arranges data into a matrix.  You can read the comment lines inside of the program to see exactly what happens at each step.

 

 

C.   Calling your M-files

Now you might want to know how to call your own M-files.  To do so, first write an M-file.  Now save that M-file to your working directory (in the Matlab folder).  You must be working in the same directory as your M-file in order to use it, otherwise Matlab cannot find it.   Now, to use your program, simply type:

 

f = lodemesh(221);

 

this means that you are declaring that a variable named ‘f’ is now equal to the output of the program ‘lodemesh’ when lodemesh has an input variable of 221.

D.   Explanation of the M-files I made

You can see more examples of M-files by opening some of the programs in the work folder.  I have written help lines for the programs that I considered useful.  Also if  you wish to look at any one of the programs that matlab already has written for it, you may open them up in the M-file editor.  Go to File and open the M-file editor to use this feature.