Miscellaneous MATLAB
Note: This post has been migrated from my old WanderTech blog. The original post contained various code snippets and examples that have been reformatted for this version.
For whatever reason I have ended up doing a large amount of work in MATLAB. In school, with controls and simulation projects, prototyping for personal projects, and some finance work back in my glory days. Throughout all of it, I’ve come across a few helpful things the hard way.
- Logical Indexing
- Read Only Parameters
- Variable Pre-Allocation and Clearing
- Object Oriented Programming
- User Input
- Commenting and Publishing
So let’s get started.
Logical Indexing
The main drawback of MATLAB, and the reason that I still think it is a good analysis and prototyping tool, but bad for production, is its speed. There are, however, some things you can do to speed up code, especially when dealing with large datasets.
For whatever reason, MATLAB is not good with loops. If you are trying to go through a large vector and set all values above 7 to be 0, the first thought to come to your mind is likely:
for j=1:length(data)
if data(j)>7
data(j)=7;
end
end
But instead do something like this:
data(data>7)=7;
It is not only much cleaner (one line!) but also way faster in MATLAB. Similar logical operations can be done with the same formatting.
Read-Only Parameters
If you are passing a large vector or matrix into a function and performing an operation on it, you are most likely going to do this:
function data=example(data)
data(data>7)=7;
But instead do this:
function out=example(data)
out=data;
out(out>7)=7;
It will run faster, especially on very large datasets.
Pre-allocate and clear variables
MATLAB is really nice for quickly throwing things together for lot of reasons. One of those is the ability to just throw more indices onto the end of a vector without really doing anything. The dynamic typing makes your life easier most of the time, but when speed is important or data is big, it can really slow things down. This is because every time you say:
data(end+1)=7;
The memory space holding data is completely de-allocated, and a whole new chunk is re-allocated for the new, slightly larger data vector. So really, pre-allocate everything with 0’s.
clear data
And then, when you are done with it, clear it. It’s so easy. And it will keep you from getting the dreaded ding and an out of memory error.
Object Oriented MATLAB
MATLAB is not a traditionally object oriented language, but there are tools available to implement object oriented code in it. I’ve found this particularly useful in making custom ’toolboxes’, so that an object can contain all of the dynamic equations of a Car, for instance, and be used as a black box which other scripts manipulate for simulations.
It can also be useful in things like prototyping large multi-population genetic algorithms. One downside here is that combining the parallel computing toolbox and object oriented programming has proven tricky for me. Still can be very useful for developing modular and flexible simulation frameworks.
User Input
Another blessing and curse of MATLAB is the ease of editing code while running it. Generally its a terrible idea to just have a line that you edit to vary between two tests, or something like that, so use user inputs. Sometimes all you need is the user to select from a menu:
userSelection=input('Pick a color:\n1: Red\n2: Blue\n3: Green\nEnter number of choice ');
Sometimes you need them to select a file:
[FileName,PathName] = uigetfile('*.csv','Select the data file');
data=load(strcat(PathName,FileName));
Either way, take the 5 minutes, and make your code flexible and usable without having to edit source.
Comment and Publish
If you are turning in your code for a class or for work, someone is going to have to parse through it and figure out what all of your cryptically named variables and obfuscated arithmetic are supposed to be doing. Make their lives easier by commenting. Like a lot. In complete sentences. Maybe even throw in some LaTeX equations.
Then when you are done, and are about to print each .m file and figure separately? Stop. Go to publish, change around your settings, publish it to LaTeX. It will automatically do some wonky things with the table of contents (uses the first line of every cell as a heading), but it will be 90% of the way to the most beautiful homework or report ever turned in.