Using Handle Graphics to Change an Existing Plot

Let’s say you have an existing plot, saved as a .fig file, and you’d like to change the width of one of the plot lines. How do you do it? Do you have to generate the plot again? Nope - you can use MATLAB’s handle graphics to update the existing figure. For more info on how to do this, see this excellent page at MIT:

http://www.mit.edu/p … e/matlab/handle.html

If, for example, you want to change the ordering (layering) of two separate plot lines, you can do something similar to:

>> h = gca;
>> get(h, 'children')
>> set(h, 'children', [ans(2), ans(1)]);

Very handy!

Back to top

MATLAB Has a Map Type…

In one of my recent coding projects, I needed a map data structure, i.e., something that would store key/value pairs - similar to a dictionary in Python. I’d been planning to write something up myself (hacked together), but a little bit of searching turned up:

m = containers.Map;

which was just what I needed. This is a hashmap implementation, which was (apparently) introduced in R2008b. Adding new key/value pairs is straightforward:

m('Jim') = 'Brother';

for example. There’s lots more - check it out by typing

help containers.Map

at the MATLAB command prompt.

Back to top

Syntactic Sugar: Using the New ‘~’ Notation

Here’s the situation: you call a function that returns multiple outputs, and you only need to use the second or third output - you’d like to ignore the rest. In one case I encounter often:

	
[dummy, idx] = max(x);
...
	

I’m interested in the index of the maximum value in the array ‘x’, but I don’t need to know the value itself. So I create a dummy variable, which hangs around unused, cluttering things up. Starting with MATLAB R2009b, you can now do the following instead:

	
[~, idx] = max(x);
	

This is the new ‘~’ (tilde) notation, which explicitly indicates (to both the programmer and m-lint) that the first output argument is unused. It’s a little bit of syntactic sugar that makes the code cleaner, and avoids the need for an extra variable. Sweet!

Back to top

LaTeX Output from MATLAB Symbolic Expressions

I’ve recently been doing a lot of work with the symbolic toolbox - some of the matrices I produce are large, and I need to get the results into LaTeX. I’d previously done this manually or with a quick shell script - but it turns out that MATLAB already has the command latex, which takes a symbolic expression and generates LaTeX output. Even better, if you name your symbolic variables with underscores, the command will generate proper subscripts! For example:

>> syms q_1 q_2 q_3 real
>> q = [q_1; q_2; q_3]
q =
q_1
q_2
q_3
>> latex(q)
ans =
\left(\begin{array}{c} q_{1}\\ q_{2}\\ q_{3} \end{array}\right)

Very handy!

Back to top

Preallocating Struct Arrays…

I frequently use struct arrays to store various types of data in my MATLAB programs. For large arrays, it’s better to preallocate space in advance - although it’s not well-documented, the easiest way to do this is to initially assign a value to the largest array element you’ll need. For example:

>>  dataset(1000).field1 = []
dataset = 
1x1000 struct array with fields:
    field1

Now, if you check, say, the 500th element:

>> dataset(500)
ans = 
    field1: []

you’ll see that space for the remaining 999 entries has been allocated.

Back to top

Undoing Plotting Operations

Recently, a friend gave me a very handy MATLAB plotting tip - it’s possible to undo the last n plotting operations for a given figure. So, if you’ve already plotted several data series, and you then, for example, plot the wrong series by mistake, you can ‘roll back’ your changes. The simple function below illustrates how to do this:

function undo_plot(h, n)
% UNDO_PLOT Undo last 'n' plotting operations.
	
if nargin == 1 
  n = 1;
end
	
if n < 1
  error('Can''t undo < 1 plotting operation!');
end
	
figure(h);
children = get(gca, 'children');
	
for i = 1 : n
  delete(children(i));
end

Note that the function requires the handle of an existing figure. To grab the most recent figure, use:

undo_plot(gcf, 2);

for example. This call will undo the last two plotting operations.

Back to top

Number of Rows, Number of Columns…

Just a shorty entry: I frequently need to determine the number of rows or columns in a matrix - you can call the size() function for this, but calling size with two arguments all the time makes my code look cluttered (IMHO). So I wrote a couple of tiny functions which return the number of rows or columns, respectively.

function [nr] = nrows(A)
% NROWS Number of rows in an array.
%
%   [nr] = NROWS(A) returns number of rows in A.
	
nr = size(A, 1);
	
function [nc] = ncols(A)
% NCOLS Number of columns in an array.
%
%   [nr] = NCOLS(A) returns number of columns in A.
	
nc = size(A, 2);
Back to top

Customized Printf Function for Debugging

I often find it useful to print conditional debugging information while a script is executing. Ideally, MATLAB would have a feature akin to the ‘#define’ preprocessor macro in C/C++ - for now, the short script below is the best I’ve been able to come up with.

DEBUG_PRINT(level, message, …) works just as fprintf does, except that debug messages are only printed if ‘level’ is set to a value greater than or equal to the value of the global workspace variable SHOW_DEBUG_LEVEL. If SHOW_DEBUG_LEVEL is undefined, no output is printed. To see debugging output, simply define SHOW_DEBUG_LEVEL as global in your workspace, and then set the variable to the appropriate integer value (based on the levels of debugging output you’ve defined).

function debug_printf(level, varargin)
% DEBUG_PRINTF Conditionally print debug info.
%
%   Inputs:
%   -------
%    level    - Debug message level.
%    message  - Message string.
%    ...      - Variable-length argument list.
	
global SHOW_DEBUG_LEVEL;
	
if level >= SHOW_DEBUG_LEVEL
  disp(sprintf(varargin{:}));
end
Back to top