Friday, March 27, 2015

Flipping the Y axes in Matlab

In most computer graphics APIs/toolkits, the default Y direction is from top to bottom, i.e. the Y origin (y = 0) is the top and increases as it goes downward. However in most scientific plots, the Y direction is the opposite. The positive Y direction is upwards.
Because of this discrepancy, there is always confusion when drawing images, especially in Matlab (e.g. imagesc). While one possibility would be to flip the data array via flipud, my preferred method is to use the 'ydir' option.

set(gca, 'ydir', 'normal');
This leaves the data as is, no flipping data, and only changes the the plot options, which separates data from presentation. (Model/View)
An interesting point is that the default value for ydir is 'reverse' which is the default direction of most graphics packages.

Wednesday, March 11, 2015

Timestamps in Matlab

Matlab has a nifty function for taking timestamps to measure the time it takes to run something. The functions are tic and toc.
You start a timer by calling tic then stop it by calling toc. When toc isn't assigned to a variable, it will print a timestamp summary to the console.
You can save a tic_id to use multiple timers.
Here is a simple example that uses the timer ID:

t_id = tic;
your_time_consuming_function();
toc(t_id)