Hi Muneer,
Thanks to advances in the MATLAB execution engine, for loops such as the one above are really quite efficient. However, with that being said there definitely a way to get this done via indexing which is marginally faster. You can first convert the subscripts (I,J) that you want to pull from your data matrix into linear indices by using the SUB2IND function. From there, you can simply grab only the linear indices that you want from the giant data matrix (40x20000 elements).
control_vect = randi([1,40],1,20000);
data = rand(40,20000);
a = tic;
my_output1 = zeros(1,length(control_vect));
for i = 1:length(control_vect)
my_output1(i) = data(control_vect(i),i);
end
toc(a)
b = tic;
linearInd = sub2ind(size(data),control_vect,1:length(control_vect));
my_output2 = data(linearInd);
toc(b)
isequal(my_output1,my_output2)
By running the above script, you will see from the tic/toc wrapped around each sections of code that the time is very low in both cases, but very clearly lower in the second case where linear indexing is used instead of the for loop. In either case, the efficiency of MATLAB is such that the difference is not noticeable.
~Zack
Best Answer