How to avoid for loops and if-statements?

Hello, I'm developing a genetic algorithm and my objective function contains many loops which increases the computation time substantially. One of them in particular is found below. Does someone have an idea of how to avoid using these for loops and if-statement?
for j = 1:d.NTeams
for k = 1:d.NTeams
for l=1:d.NTeampairs
if(d.Distances(l,1) == j) && (d.Distances(l,2) == k)
totaldistance = tabley(j,k)*d.Distances(l,3);
end
end
end
end
d.NTeams equals 38 and d.NTeampairs equals 1444. d.Distances is a 1444x3 matrix in which the first two columns represent all possible team combinations and the third column contains the traveling distance between these two teams. tabley is a 38x38 (d.NTeams x d.NTeams) binary matrix. If two teams play in the same league, then their corresponding value in the tabley matrix equals 1, otherwise 0. The goal of the problem is to group all these teams into a couple of leagues making sure that the total traveling distance (totaldistance) is minimized.
Thank you

2 Comments

Look into meshgrid. You can generate a matrix with all combinations of indices with it, so you can check all of them in one go. To replace the if-statement, you can use logical indexing.
(Note that totaldistance is currently overwritten every loop where the if is true. If that is intended behavior, a middle ground solution would be to loop backwards and break when you get a value.)
Thank you, that helped a lot!

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 7 Jan 2018

Commented:

on 9 Jan 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!