Sunday, July 27, 2014

Marvelous Matlab Must-haves: Part 2

A continuation of my Matlab series from what, gasp, only two weeks ago?  I'm setting up some really unrealistic standards for myself here, mostly because I've been copy-pasting from the original partially-written big long ginormous* post and lightly editing from there.  So when I hit the 1.5 month gap between posts, you'll know I reached the point of actually having to write something.  The horror.

*Fun fact - "ginormous" is apparently a valid word in Google's spell-check

In keeping with the theme of the first post of this series, these are all stupid little things that are not particularly artful or earth-shattering, but they are dang useful tool/concepts that really helped me to be a lot more productive once I understood them.  So here's hoping this also helps you!

To read Part 1 of this series in which I covered the joys of Google and debugger, go here.  To read the currently non-existent next post, don't go here.

And now.....

Functions and Scripts and Cell Scripts, oh my!

You were expecting the Wizard of Oz, weren't you?  Life is full of dissapointments, isn't it?  On the other hand, you may enjoy reading about the Venezuelan Trench Moose.

Functions:
Stuff in, stuff out.  Basically a make-your-own version of Matlab's functions (think "plot","mean", etc.).  You feed in variables, crunching happens, and it plots what you tell it to plot and spits out what you tell it to spit out*.  The thing I like about functions is that they don't spit out all the intermediary variables into your nice clean workspace.  So if you've got some calculation that requires 17 steps, you only have to deal with step 1 and step 17.  It's also possible to stick your custom functions inside other functions, thus giving you 9 or 17 or 200 less lines of code to sift through.

*And therein lies the danger of coding, because computers are like extremely literal-minded 4-year-olds with access to ALL your data.  They follow instructions VERY well.

Of course the catch is that if something goes wrong in the middle, you don't see it.  Which is why we need debugger!  And because it can sometimes be obnoxious to have to run functions over and over and over again to get them right, I'll sometimes work out algorithms first in a....

Script:
Stuff in, stuff happens and all of it (variables, plots, etc.) gets kept.  Basically it's a faster way of executing a whole bunch of commands in the workspace (the place next to the >> symbol where you generally enter single commands).  For this reason I like using scripts to record how I made figures*, especially if they're finicky one of a kind figures.  I can keep track of what data I used and exactly how I plotted it, so if I lose the image file or need to alter something, I don't have to start from scratch.

*Grad students! THIS IS IMPORTANT!!! LEARN FROM MY MISTAKES!!!

In the same vein, scripts are incredibly useful for batch-importing data, or basically any task where it's a pain to do the steps one at a time in the command line, but you're likely not going to do it again so it's not worth the effort to create a slick function.

Run the whole script by either pressing the green "play" button at the top, or by typing the name of the script file in the command line and pressing Enter.

Cell Scripts:
Like a script but with structure.  You can split a script into cells by putting "%%" in a line between cell blocks.  You can then run the script a cell at a time by placing your cursor inside the cell and hitting Enter to run the cell or hitting ctrl+Enter to run the cell and then advance to the next one.  Cell scripts are mostly useful for keeping an unruly script organized, or for situations where you're going to want to execute part of a script several times (say for adjusting parameters on a figure).  HOWEVER, you can't use debugger in cell mode (at least I think you can't), which is annoying.

Command history

Another sanity saving tool.  Too lazy to keep hitting up in the command line to get that previous command back?  Just go find it in command history, and double click to execute or copy-paste it in the command line if you want to alter something.

I also find this highly useful for building scripts and functions, and just keeping track of what I've been doing.  When I'm processing data at work, I'll typically keep a chart going with fields for variable, the exact command I used to create that variable, and comments on the outcome*.

*i.e. Wow.  According to this gravity meter the world clearly just exploded.

If you're not being good and keeping track in a handy chart, you can also word-search the command line to try to find just what exactly you did to create that graph two months ago!  Unfortunately, it only goes back so far, so better to keep a chart/script going...

Save

Save the workspace!  SAVE THE WORKSPACE!!*  Preferably BEFORE you accidentally close Matlab after wrangling that data set for three hours.  Instructions here.  This is incredibly useful if you ever have to go back and look at old data, or heaven forbid reprocess it.

*Bonus points if you figured out this is what I was referencing.  I hope from now on ALL of you read anything beginning with "save the" in Julia Child's voice.


Next up: Plot editor, the File Exchange, and Concatenation

Sunday, July 13, 2014

Marvelous Matlab Must-haves: Part 1

I do believe at some point I may have promised a post on the joys of Matlab.  Well, that long awaited promise shall now come to fruition.  I have assembled, in no particular order or completeness, a jumble of some features and functions of Matlab that have proved of immense use to me in avoiding baldness when using the glorious program.

Computer programming is perhaps best done by those with fast-growing thick hair.


I initially planned to make this all one blog post, and then realized a) it was going to be a really long post that might never get published and b) if I split it up I could make it look like I was all prolific and stuff.  SO. Part 1 of the series!

If you have used Matlab extensively, many of these will no doubt be old hat to you, but if you're just learning and are fearing for the fate of your remaining cranial covering,  I hope this post (and those to come) will be of some aid to your beleaguered follicles!

Google

Perhaps a bit of an obvious one, but I include this because, just in case you needed to hear it, yes, it is okay to search the interwebs for ideas/help, and no, it does not mean you suck at programming and will never get it.  Google searching "Matlab how to do xyz" is a surprisingly excellent way to figure stuff out.  About 9 times out of 10, someone has already asked the same question, someone's written a function on File Exchange (more on that later), or there's a built-in function in Matlab, because Matlab is awesome.  The other 10% of the time you can usually get a partial answer, or at least something that will get you on the right track to the correct question.

Debugger

Learn how to use Matlab's debugger!  Seriously!  You can use the debugger in both functions and scripts (but not cell scripts).  (I'll be explaining the differences between functions, scripts, and cell scripts in a later post)

The most basic way to use debugger is to tell Matlab to enter debug mode when it hits an error.  This is instead of Matlab hitting an error and making that annoying "ting!" sound and throwing up red script with some highly technical error message that tells you nothing because you've been booted out of the function that has the variable that caused the error, but now you can't LOOK at that error because you've been booted out of the function.

But if you stop in debugger, all is well!  The variable is there, in all its empty array glory.  *sigh*.

You can get to this most useful of features by going to the "debug" menu in the editor window (the window where you write functions and scripts), and selecting "stop if error".

If your code isn't dying because of errors but is throwing up completely nonsensical data, you can also insert what are called "breakpoints" so that the function/script will stop in debugger at that point so that you can look at all the variables and make sure they're what you thought they were!*  To insert a breakpoint, click on the little line next to the line of code where you want the function/script to stop, and a little red circle will appear.  The function/script will execute everything up until that line, and then stop.  At this point you can discover that your squid variable is 10 times larger than it needs to be, turning your moose variable into the dreaded "NaN".  Or some such.

*Spolier alert - they're NEVER what you thought they were.  Ever.

You can also make a conditional breakpoint by right clicking the line and selecting "Set/Modify Condition" (you'll get a yellow circle).  This is often useful for loops, where for instance you know everything is just dandy up until i = 10 (out of 23523430 iterations) at which point all hell breaks loose and demons infest your variables and you can't remember how to properly call the Matlab "exorcise" function*.  In that case you'd set your conditional breakpoint to stop on that line when i==10, and figure out just what the heck is going on!

*Because I haven't written it yet.

Next up: Functions, Cell Scripts, and Scripts, oh my! 

(....sorry.....)

Stay tuned for more to come, at no particular scheduled time in the hopefully not-too-distant future!