MATLAB: Iterating a loop many times

for loopwhile loop

  • I'm not sure how to iterate this loop 1,000 times:
  • —a=randperm(20)
  • LOOP STARTS:
  • — code that swaps 2 elements in 'a' randomly to make a guess 'amaybe'
  • — if fun(amaybe)>fun(a)
  • anew=amaybe; (guess is kept)
  • elseif fun(amaybe)<fun(a)
  • anew=a; (guess is rejected)
  • end
  • LOOP ENDS
I need to make 1,000 guesses (swapping 2 elements each time) until the final guess should have the highest fun value. How do I iterate the loop that many times? And should I use a for-loop instead of if/elseif?

Best Answer

I would use a for loop because (1) it seems you need to do 1000 iterations and (2) the comparison operation (whatever it is that ‘fun’ does) doesn’t affect the number of iterations.