The entire site has been mapped to the above URL. Further posts can be found there.
- 10,852 hits
The entire site has been mapped to the above URL. Further posts can be found there.
If you’ve followed this Enhanced Matlab Plotting Series, it should be apparent that the mPlot class we have created is the definition for a custom object. That is, we have created an object (strictly speaking its the definition for an object) that has user-defined properties (like fields within a struct) and user-defined methods (functions) attached to the object. If you started this series with no knowledge of classes or object-oriented programming, then some portions of this series may have been a bit fuzzy…..and I’m glad you’ve stayed tuned for this long as this part of the series we are going to point out some of the obvious and not so obvious advantages of using object-oriented programming (OOP). I should mention, that the syntax for OOP used in these examples was released in Matlab 2008a. So this functionality is not available in previous versions of Matlab. FYI, you may see individuals commenting on classes in Matlab before 2008a. The syntax and methodology for using those classes is still supported in later versions of Matlab, but will not be used in these tutorials.
This part of the series we are going to focus on inheritance. That is, we are going derive another plotting class from our mPlot class. Instead of going through all of the generalized talk, lets use a practical programming problem to understand inheritance. If you’re familiar with the mPlot class, you know that back on day one we pre-defined a number of marker and line colors. Check out the method buildProperties() if you’re not following – https://matlabmafia.wordpress.com/2010/11/27/enhanced-matlab-plotting-series-part-i/. Lets suppose that others may not share my taste in color selection. So you have the mPlot class, but can’t live with the pre-defined colors. Lets also say that you want to automatically enable auto-incrementing via the isAutoIncrementing property (Note that this is currently disable in the mPlot class definition we have been using). Therefore our goal is to 1) redefine all of the colors inside the mPlot class and 2) enable auto-incrementing upon instantiation, but retain all of the other class functionality.
Before we actually dive into code and attain our goal, lets answer the “why use inheritance” question; because I know someone out there is saying “its simple, just delete all of the colors inside of the buildProperties() method and type in new colors.” While it is true that this would work, inheritance provides us with a much more dynamic and robust solution.
Lets say for example you choose to alter the color scheme and change the class name from mPlot to newColorPlot; by alter, I mean physically delete all of the color definitions and replace them with new definitions. So now we have a class named newColorPlot with the desired colors. But what happens when the creator of mPlot releases a new version with extra functionality and bug fixes? Well, one might consider tediously merging the two files into a composite file that functions with the new mPlot functionality, but has the newColorPlot colors. While this would work, it would be time consuming and could possibly lead to errors. The other option is to completely ignore the update to mPlot. But in this case we risk leaving bugs throughout our newColorPlot class. Inheritance gives us the best of both worlds. It means we can implicitly accept all of the new functionality and bug fixes from mPlot without touching any code. All that needs to be done is replace the old mPlot class definition file with a new one.
If you want more detail, check out Matlab’s website regarding inheritance and building on other classes at http://www.mathworks.com/help/techdoc/matlab_oop/brdf7kt.html.
Lets start off by simply creating a new class that inherits from the mPlot class. This is show below. Notice that in the first line we have used a logical “and” (aka “&”) to inherit both the handle class (don’t worry about that for now) and the mPlot class. So there you go, we’ve inherited from a class.
Next, lets compare an instance of mPlot with an instance of our new class that inherits from mPlot. They better be the same….that is, the must have the same properties and methods. This is shown below.
Now that we have the new class, lets redefine the colors. For simplicity, the jet function is used to automatically generate a set of colors. We’ve also enabled auto-incrementing by default. As a side note, what is actually happening is the mPlot constructor is being executed once the myInheritedmPlot object is instantiated. Next, the myInheritedmPlot constructor is being executed. This overwrites all of the marker edge colors and marker face colors. It also changes the value of the isAutoIncrementing property.
Simple as that….we are finished.
Here we are simply going to plot with an mPlot object and a myInheritedmPlot object to show that they have different colors and that the auto-incrementing state is enabled by default. The code below
produces the plot.
Its evident that both of the objects have behaved in a similar fashion, but the color scheme has now been changed.
In this simple example, we derived myInheritedmPlot class from the mPlot class definition. The color scheme of the new class was altered. Substantial more functionality could have been explored, but this simple example gets one on their way to creating derived classes. Stay tuned!
Last post we added several helper methods that allowed for easy interface with current line settings. Think of that functionality as low-level relative to what we are going to discuss this post (by low-level I mean simple or core functionality). The method we are going to add this time serves to provide much higher level functionality (higher level being more advanced and specific…but less reusable). This new method is going to place the mPlot object into a state, with a specific behavior. This will be similar to the auto-incrementing state that was discussed in a previous post in this series.
The state we are going to cover today will deal with holding a particular marker and cycling through other line properties. Similar to last time, this can come in handy when we need to compare multiple runs of an experiment, multiple filters/controllers or models, etc.
Before jumping directly into code, lets go through how this functionality should behave. We want to enable this state and have our mPlot object 1) set and hold a particular marker style and 2) automatically increment through the other line properties as we feed data to the object via the plot method. Once we disable this state 1) we want to move to the next set of unique line settings and 2) return auto-incrementing to its previous state (leave on if it was on and turn off if it was originally off). Simple enough….time to code.
The code below shows definitions for the properties to be used. These properties will allow use to enable and disable (via isHoldingMarkerStyle) holding a particular marker style (the heldMarkerStyle). The private property isAutoIncrementingPreviousState will store the previous state of the objects auto-incrementing property. The fact that this properties setAccess state is private means that users of an instantiated object can NOT change this property.
With the isHoldingMarkerStyle property, we are going to take advantage of set/get methods for the property. In short, this simply allows one to run a method (execute some function) when a property value changes. Check out the code below. We have performed some simple marker validation after enabling the state. Notice near the bottom we have defined a new method for checking if a markerType is valid.
More details regarding set/get methods for properties can be found on the Matlab OOP documentation website at http://www.mathworks.com/help/techdoc/matlab_oop/brgsek9-1.html.
Last but not least, we need to actually write the code to apply the marker of interest. This will be performed inside of the plot call within the mPlot class. In the code below, notice that we have added an intermediate variable named currentMarker. This value is toggled to reflect the desired marker selection technique (default or current held marker).
To test this functionality out, consider a situation where you need to overlay several model predictions with a measured data set. In this case, we will draw the models with a line/no markers and the measured data with markers.
The functionality we added above focused on holding a particular marker type. Similar behavior could be added for all of the line properties (line style, marker edge color, etc). For the next set in this series we will add in other high level functionality. Within the next couple of posts, we will diverge for a post and explain inheritance. It will be tied into this series; we will use this functionality to help one personalize this class. Let me know if you have any questions or comments.
During the last post we extended mPlot formatting to axes and figure objects. This post we are going to add some helper methods to the mPlot class. Recall back in the second post of this series we added several methods for interfacing with the plotCounter variable. While these methods did not do anything magical, they were extremely helpful and made interaction with the class easier. The methods that we are going to add this time will allow easy access to current line settings, such as marker size or marker type.
After using this class for some time, I found myself continually altering specific properties within the mPlot class. While this worked, keeping track of the plotCounter indexing (to ensure modifications were to the current line settings) was a hassle. Hence methods to interface with these properties made sense. The methods we are going to add this time will be 1) setCurrentMarkerType, 2) setCurrentMarkerSize, 3) setCurrentLineStyle and 4) setCurrentMarkerEdgeColor. As the name of each of these methods suggests, they will change some property of the current line.
The code for these 4 methods is pretty straightforward. Once again, the content is nothing spectacular, but incorporates handy features that you will come to use. Notice we’ve added a new methods block to the class. This is not required (the code could be added to any methods block with the desired scope) but a useful habit for bundling methods designed to perform similar tasks.
…..take a minute and study the above code. Some error trapping checks were put in place to ensure that the input arguments are valid marker types and line styles. Other than these lines, most of the methods could be reduced to one-liners.
Example Using Methods
Lets work through an example to demonstrate some uses for this newly added functionality.
Imagine we have 3 different filters that are of interest. We would like to display the magnitude response of each filter for several different filter orders. Suppose we are testing filter orders of 10, 20 and 30 and we want the markers to be circles, squares and triangles, respectively. So our marker type will reflect the filter order and the marker/line color will be indicative of filter type. The code below should get the job done.
I’ve outlined several sections of the code in red. This is the code that handles the plotting. The other sections are merely constructing filter coefficients and evaluating the magnitude response of the filters. The code produces the result below.
Notice that each marker reflects a particular filter order….as we intended.
The other methods that we’ve added could be explored in more detail; but for now the above example demonstrates the functionality in a practical form. So after 4 parts to this series we have constructed a framework for our plotting class and fleshed out an amount of functionality. Stay tuned for more!
Thus far we have focused on controlling the appearance of lines on a Matlab axes. Let’s take it one step further and work on the appearance of the figure and axes. This will expand control beyond simply lines and allow one to achieve an overall presentation that is desired. First lets add a property that will determine if parent formatting is to be performed. Here the axes and figure are considered the parents.
Notice that we’ve set the isFormattingParents property to 1 inside of the constructor. This means that by default parent formatting will be enabled.
First create a function named formatParents. The job of this method is to house the code that performs the axes and figure formatting. Next we need to call this method within the plot method if parent formatting is enabled. The code to perform these actions is shown below.
One handy feature of Matlab classes is the ability to view the available properties and methods at the command line. This can be done by first creating an instance of a class. After typing the object name followed by a period and then the tab key, Matlab will bring up a list of the properties and methods associated with the object. This is shown below.
Having such a feature available means that less typing is required to get a method name or property name on the screen. In turn, this makes more descriptive property and method names attractive (you may have noticed my wordy variable names). For the Visual Studio user’s out there, I know you are all scoffing at this weak version of intellisense; and I’m right there with you! I hope to see a more intellisense-like display of object information in future releases of Matlab….but this is a step in the correct direction.
Back to parent formatting….As we have done in the past plotting series, a simple loop around a plot call is used to produce the plot shown below. Notice that the background color is now gray and gridlines are drawn on the axes background. The text on the axes has also been enlarged.
These are merely settings that I prefer. Any desired parent formatting could be performed.
Up to this point we’ve created a functional plotting engine that controls many aspects of visualizing data. In this example, we added figure and axes formatting. This type of formatting could be greatly extended to include other objects outside of merely figures and axes. Other candidate objects that one could format would include axes labels, figure titles and legends to name a few. More to come next time!
Last post we defined the mPlot class and added properties to define the visual appearance of line objects. A method to draw data on the current axes object was also added. This time we are going to add some handy functions to make interaction with the mPlot object easier.
As we saw last time, plotCounter is used to determine which visual styles to apply to the current line. Recall from last time that we had to increment the plotCounter property external to the class….as shown below.
While we’re on this topic, add one property named isAutoIncrementing. This will be a boolean value, either 1 or 0. If the value of isAutoIncrementing equals 1, a method will automatically increment plotCounter each time a line is drawn to an axes. Notice below that we had to add an if-then statement within the plot function to increment plotCounter if auto-incrementing is enabled.
This property will also need to be initialized within the constructor of mPlot. This will eliminate the need to call an increment method every time we plot the next line. Of course, there may be some cases where you don’t want this type of functionality. In that case simply set isAutoIncrementing to zero and you’re back in full control.
The short lines of code below will be used to test out the new methods within mPlot. Check out the comments for more information….but all we have done here is 1) plot on an axes while manually incrementing, 2) reset the plotCounter to zero, 3) enable auto-incrementing and 4) plot on a different axes.
After executing the code the plots below are produced.
So regardless of technique, both produce the same result. But when plotting multiple lines on a single axes, auto-incrementing can be advantageous. One may even choose for this to be the default. In this case, simply set isAutoIncrementing to 1 inside of the mPlot constructor. Then each time you instantiate mPlot auto-incrementing will be enabled.
In the next part of this series we will extend formatting beyond lines; we will dive into altering the appearance of the axes and figure.
We all know about Matlab’s unparalleled plotting capabilities. The signature 3-D surface plot sitting on our desktop as a Matlab icon is a daily reminder. The intent here is not to delve into surface or mesh plots, but to focus on simple 2-D plotting.
First let me give a little background about how this plotting layer came about. As an avid Matlab user, I spend most of my days staring at monitors filled with m-files and plots. Over time I began to realize that I preferred all of my plots to appear a certain way; and was spending much of my time formatting figures, axes and lines. So I decided to develop an engine within Matlab that would handle all of my plotting. You can think of this as a layer between the coder and the low level Matlab plotting and formatting functions. Almost immediately after creating this layer I recognized that I was substantially more efficient, and to top it off everything appeared exactly the way I wanted; too good to be true, right?. After working with and developing this layer for some time now, I’ve added a substantial amount of functionality….I’m at the point where I couldn’t imagine having to revert back to interfacing directly with the low-level Matlab plot function. So, in this series of articles I hope to explain what this magic “layer” is that I’ve been referring to.
Before diving in, I must warn you that this “layer” I’ve been referring to is actually called a class. Classes are used in a form of programming termed Object-Oriented Programming (OOP). But don’t shy away simply because you haven’t used them. We will walk through how the class is created to some extent. I was brought up in Mechanical Engineering (ME) and know that ME’s (and other engineering disciplines) are rarely exposed to object-oriented programming (as I usually get the blank stare when I bring it up around my ME colleagues). If you are interested, check out Matlab’s website about OOP @
They do a nice job of providing an introduction and explaining the syntax. Since OOP is something foreign to many branches of engineering, Matlab OOP may be one of our series in the near future.
Ok, so let’s get started. In this first part of the series we are merely going to predefine a color scheme for our plots; specifically, line and axes properties. It sounds simple, and is…but I have found this to be very useful for daily Matlab chores.
Let’s first begin by creating a blank class with an empty constructor (a function that runs when you instantiate the class), a few properties (attached variables local to our class) and one method (aka function).
Next lets add some properties to our class. These properties will be used to define the style of a Matlab line object. The comments in the code explain the intent of each property.
For now, just set GetAccess and SetAccess to public. We will discuss what this means later in the series. Also, the use of these properties may be a bit fuzzy at this point. Keep going and this will become clear as we flesh out these properties.
Now lets incorporate a method (function) used to plot data. This function will behave similar to Matlab’s plot function in that it accepts x and y vector data pairs as input arguments. This plot function will draw the data onto the current axes while assigning the line properties defined within the class.
Now all we have to do is define a few line properties and the class should be ready for action. For this task we will define a function that builds our color, marker and line type arrays. This will then be called within in the constructor of the class. Hence once the class is instantiated these properties of the class will get defined. This is shown below. We have defined unique properties for 4 different lines within the buildProperties function. Notice the last statement initializes the plotCounter property to zero.
Let’s try out the new mPlot class. As shown below, instantiation of the class creates an instance of our mPlot object. All of the properties that we have defined within the class definition file show up within the object.
Next test out the plot method. The simple loop
And that is it. We now have a basic plotting engine!
To this point we have assembled a plotting class containing 4 pre-defined line settings. We’ve also added a property to keep track of which line setting to apply to the current x-y data pair. Lastly, a plot method was incorporated that draws a line on the current axes object with the specified line settings. Next time we will work to enhance the class by adding further functionality.