MATLAB Tips and Tricks

Over the course of my graduate work, I’ve spent a fair amount of time with MATLAB.  These are a few small tricks I wish I had known from the beginning.

Preallocation

I am a believer in preallocation.  For a particular application, I read in about 13GB of data from a file into a 4-D matrix (this was running on a machine with 32GB of memory).  Before preallocation, I let the process run for about 10 hours, and it still hadn’t finished.  With preallocation the process finished in about 20 minutes.  That’s an improvement of at least 3,000%!

Permute

The permute function can be quite handy – it can shuffle around the dimensions in a matrix with a single function call.  Consider the following matrix:

m_one = rand([2 5 4000]);

The size of this matrix is reported as 2x5x4000 in MATLAB. Now, we can shuffle the dimensions. Let’s make it a 4000x2x5 array:

m_one = permute(m_one, [3 1 2]);

The permute() function takes the array to shuffle around, and the new order of dimensions. In this case, the 3rd dimension moved to become first, 1st dimension second, and 2nd dimension last so that a 2x5x4000 matrix becomes a 4000x2x5 matrix.

Vector notation

Be careful, though: as handy as permute can be, it’s easy to use it inefficiently.  Remember that 13GB 4-D matrix?  I ran permute on that, and memory usage immediately doubled.  In general, I recommend creating the data the right way first! It will save a lot of headache (and RAM) down the road.

If you desperately need only a subset of dimensions, an alternative solution is to use MATLAB’s built-in, efficient vector notation.  For example, to extract the first and third dimensions for a single 2nd-dimension element, just use

m_two = m_one(:,1,:);  

The one downside here is that you’ll end up with an annoying singleton dimension that can frustrate other builtin functions like plot. The squeeze function will rescue us.

Squeeze

Squeeze is cool.  After running the previous code, size(m_two) shows us that m_two is a 4000x1x5 matrix.  We could use indexing to access all these elements, but squeeze will make life much easier – it will remove the singleton dimension in the middle.

m_two = squeeze(m_two);  

Now, size(m_two) tells us we’ve got a 4000×5 matrix and using the matrix just got that much simpler.

Removing elements from vectors and matrices

There are times when you want to discard elements from a vector or matrix.  I used to do this by creating a new variable to hold just the elements I wanted to keep.  Obviously, there’s a better way.  Let’s remove all the elements of a matrix that are less than 0.5.  It’s insanely easy:

m_three = rand(1,1000);
m_three( m_three < 0.5 ) = [];

Now, size(m_three) gives 1x2023.

Conclusions

If you haven't noticed yet, MATLAB is all about the matrices. Understanding how to efficiently operate on subsets of matrices will give you huge returns in performance. Learn how and when to use permute, squeeze, and vector notation and you'll be well on your way. Anything else you think should be on this page? Let me know in the comments!

P.S. This article is a transfer of most of the content of an article on my old website.

, , ,

2 Comments

DRM Pokes Me in the Eye and the Funnybone

I’ve installed Windows 7 Professional (RTM) on all of my computers now–two laptops and two desktops. Overall, it’s an excellent operating system. Memory management appears to have improved significantly, UAC prompts are sparse, and of course the UI has some nice tweaks. Oh, and most system updates don’t require a reboot.

I need to vent about one thing, though, and it may seem small but my goodness it is frustrating. Kind of like getting poked in the eye, or slammed in the funny bone, or like both happening at once. That one thing is the so-called broadcast flag, where broadcasters can flip a digital switch and prevent end users from recording content.

I have a Hauppauge WinTV-HVR 1600 TV tuner with one analog tuner and one ATSC tuner. It worked flawlessly under Windows Vista. We never once had a problem with the broadcast flag.

Now, though, when Emily tries to record an episode of “What Not To Wear” or “More to Love” (I mean, these are seriously popular shows and you can see how broadcasters would want to be REALLY careful about not letting people–oh, the horror–record their precious TV shows and possibly watch them at a later time)–it’s these shows that will record for 5 minutes then we get a little notice in the taskbar: “A recording has been cancelled” and then in Media Center, this now-dreaded popup: “Restrictions set by the broadcaster, yadda-yadda-yadda”:

recordedtv

In some cases a re-run will record just fine later that night.

I think–I hope–this is a bug somewhere, since as I understand it Vista Media Center obeyed the broadcast flag and we never saw this issue.  But, since Windows 7 is so new, and technically isn’t even publically available (my copies are perfectly legitimate), there isn’t much discussion going on and certainly not about this problem.  So, I’m not sure if it’s a driver problem, a Media Center problem, or what.

So poke my eye out, media  conglomerates, operating system, world at large.  Cheap-shot my funny bone.  I don’t care.  Mostly.

P.S. “Food Lovers Fat Loss…” just happened to be on this morning when I needed a screenshot for the blog.  I mean it.  Seriously.

, , , , ,

2 Comments

RSSPhoto: A WordPress Widget

I’ve made a WordPress widget called RSSPhoto that pulls images from photoblog RSS or Atom feeds and displays a thumbnail in the sidebar (I’m using it in my sidebar).  I mentioned the beginnings of this project a couple posts back.  That one was pulling images straight out of my database though.  This version is more generic and uses the SimplePie PHP library for parsing feeds.

Even though I say it pulls from photoblog feeds, really it can pull from any feed–it will just pull one of the images out of the content of a feed item.  I’ve used it to pull Flickr RSS feeds and a couple other random ones.  I also installed it easily on Emily’s blog.

Check it out on my new Projects page (direct link).  If you have a WordPress blog, try it out and let me know how your experience was.  I’d definitely appreciate any feedback.

, , ,

6 Comments

Plugins and Widgets and WordPress–Oh my!

From my last post you know I’m trying to figure out the best configuration of my domain and subdomains.  I’m leaning toward the blog as my principal domain content with the photography blog as a linked subdomain.

sidebar

To sleep well at night with this change, I need a good way to interface my photography with the blog.  After testing a few options, I decided to try developing a WordPress Widget to display the most recent photo.  It was surprisingly easy!  I thought I might document a bit about the design of a WordPress widget.  I know my audience (consisting mostly of family) has really been hoping for a technical article with some code to sink their teeth into.  Right?

To really understand widgets, you should play around with them first in your own admin section, under Appearance->Widgets.  You can drag and drop from available widgets to the sidebar or footer to define the contents of those areas of your blog. You’ll notice when you drag a widget, a form appears with some fields to define.

On to creating a widget.  First, make a directory to hold all the plugin files in the wp-content/plugins directory.  Mine, for example, is wp-content/plugins/skphoto/.

Second, you need to define a class that extends WP_Widget, and includes a constructor function, widget function, update function, and form function.  This same file should also register the widget.  Here’s an outline of what that looks like:

class WidgetName extends WP_Widget
{
  /* constructor */
  function WidgetName() {}

  /* display the widget */
  function widget($args, $instance) {}

  /* save widget settings */
  function update($new_instance, $old_instance) {}

  /* edit form for the widget */
  function form($instance) {}
}

function WidgetNameInit()
{
  register_widget('WidgetName');
}
add_action('widgets_init', 'WidgetNameInit');

See Jesse Altman’s tutorial post for details on these functions.

I do want to give a bit more information about the widget function. If you want to access your MySQL database from within the widget function, you’ll need to add global $wpdb; to the top of your function.  Then, you can use standard WordPress database functions to pull data out.

Here’s the basics of my widget function for reference:

  function widget($args, $instance){
    global $wpdb;
    extract($args);
    $title = apply_filters('widget_title', empty($instance['title']) ? ' ' : $instance['title']);
    $feed_url = empty($instance['feed_url']) ? 'http://photography.spencerkellis.net/atom.php' : $instance['feed_url'];

    # Before the widget
    echo $before_widget;

    # The title
    if ( $title )
    echo $before_title . $title . $after_title;

    $sql = "SELECT `path` FROM `photos` ORDER BY `date` DESC LIMIT 1";
    $path = $wpdb->get_var($sql);
    echo "";

    # After the widget
    echo $after_widget;
  }

Finally, activate your new plugin in the WordPress Plugins section. Then go back to the Widgets where the new widget will be available to drag and drop.

So there it is.  Easy-peezy, right?  Just a few lines of code, as I always like to say.  Here are a few resources if you want to explore on your own:

So I’ll be looking for your thoughts.  What do you think about this solution for a home page?

, , ,

No Comments

Joining Prodigious in the Whirl of Identity Crisis

Here’s the deal. I’ve got four websites right now: www.spencerkellis.net, blog.spencerkellis.net, gallery.spencerkellis.net, and photography.spencerkellis.net. That’s really just too many websites for one person–I mean, who are we kidding here?  How many ways are there to upload photos to a website? A thousand spencer’s on a thousand typewriters… How many PhD students does it take to… and the list goes on.

Is this narcissism at its finest or what?

I like and plan to keep the blog and the photography site (photograpy.spencerkellis.net). What do you all think about the gallery and the www.spencerkellis.net? And don’t worry about my feelings, fragile though they may be. It’s not like I spent 5 years of my life working on www.spencerkellis.net.

BTW, I’ve been making an attempt to post photos more regularly to the photography website.  The last 6 are from our vacation to Oregon if you want to check them out.

,

3 Comments