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 :
5 times slower… too much to ignore!
From now on, no sub2ind to me!