Friday, March 25, 2011

~ in Matlab: not just for NOT

When reading Steve's article on the irregular behavior of Matlab's size() function, I was reminded of a neat trick.

Frequently I call a function and only use one or two of its output arguments. In many cases I use the first couple of output arguments, but occasionally I want to use, say, only the second output argument. If I assign the first output to some variable, I now have a meaningless variable floating around, taking up space, and potentially causing problems. A much more elegant solution is to call the function like this:
[~, output] = myFunction(input);
In this way, the first output argument disappears while the second is saved to the variable output.

If you'd like, you can read articles on the same topic by Matlab geniuses Loren and Steve.

2 comments:

  1. Ooh, I like that one too. I think it even increases speed because it will skip the part of the function that calculates that if possible. Used it for the checkers robot a lot

    ReplyDelete
  2. Hey, that's useful, thanks! Now if only my lab's license actually allowed grad students to download and install new versions of Matlab off the Mathworks site, I could upgrade to a version that supports this.

    ReplyDelete