MATLAB: Speed up indexing without using a loop

find functionmatrix indexing

Hi all,
I would like to know if there is a way to speed up indexing procedure in the following code:
N; % given nx1 matrix with some values
D = inf(n,1);
D(1,1) = 0;
M = zeros(n,1)
while sum(M)~=length(N)
D_adj = D;
M_index = find(M);
D_adj(M_index) = inf; % or any very large number
[~,index_m] = min(D_adj);
M(index_m) = 1;
FOR LOOP % another code for a FOR loop to update values in matrix D;
end
Essentially, for every iteration within WHILE loop, I update a corresponding element of matrix M (by allocation value of 1). My main problem and what slows down my code is the procedure for computing M_index, updating the corresponding elements in matrix D_adj (by allocation value of inf so that they are not taken into account when computing the min value of all elements in matrix D_adj that have zero value in matrix M), and finding the index (of the min element in D_adj) in matrix D. Do you have any suggestion on how I can improve these operations?
Thanks in advance!

Best Answer

Maybe logical indexing is faster:
N; % given nx1 matrix with some values
D = inf(n,1);
D(1,1) = 0;
M = false(n,1);
while ~all(M)
D_adj = D;
D_adj(M) = inf; % or any very large number
[~, index_m] = min(D_adj);
M(index_m) = true;
FOR LOOP % another code for a FOR loop to update values in matrix D;
end
Remember the golden rule of optimizing code: Use the profiler at first to find the bottleneck of the function. If you accelerate a part of the by a factor 2, but this part needs 2% of the processing time, the total speedup is 1% only.
I doubt, that this indexing is the bottleneck of your code. But logical indexing should be at least faster.
I guess, that the part hidden behind "FOR LOOP" can be improved such, that the new minimal value can be found by a cheaper method.