sub2ind or not ?

Today I used sub2ind function while I was programming in MATLAB and thought for a second… am I being just lazy or doing what sub2ind does by myself may be faster?

I stopped my work for a little, test it and the results were as I expected… sub2ind is slower than doing it by yourself!

You can try it for yourself. Here is a sample code, save it and Profiler it:

clear all

max_n = 10000000;
XX = randi([1 max_n], max_n, 1); % row indices 
YY = randi([1 max_n], max_n, 1); % columns indices

idx = sub2ind([max_n,max_n], XX, YY);
idx2 = (YY-1)*max_n+XX;

A = sum(idx-idx2) % just to make sure MATLAB computes idx and idx2

Profiler-ing it gave me the following output :

sub2ind

 

 

 

 

 

5 times slower… too much to ignore!

From now on, no sub2ind to me!

 

Advertisements
This entry was posted in Computer Stuff, MATLAB and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s