MATLAB Answers

0

How to ignore a part of a code within loop after first iteration?

Asked by Seyyed Ali on 26 Jan 2013
Hello all,
I have a question which seems to be simple. I have a for loop where I call different functions at each iteration. Some of these functions are only needed to be used at the first iteration if a certain condition holds. One way to solve this problem is checking the condition with "if" statement before calling the related function, but I am wondering if there is any other way to take care of this since I have more than 10 functions with the same situation (with different condition of course)? As an example, please take a look at the following pseudo code:
MATLAB code
for Iteration < Generation
...
if ('certain condition 01 holds true')
output = function01(arguments)
end
...
...
if ('certain condition 02 holds true')
output = function02(arguments)
end
...
...
if ('certain condition 10 holds true')
output = function10(arguments)
end
...
end
If I have, lets say, 10000 iterations, each of these "if" statement should be evaluated 10000 times which increase the computation time significantly. Is it possible to use object-oriented programming and classes instead of functions to make it better and probably faster?
Thanks, Ali

  1 Comment

Just how long does it take to evaluation the condition? I would think you could evaluate 10 conditions 10 thousand times (iterations) in a fraction of a second.

Sign in to comment.

1 Answer

Answer by Matt J
on 27 Jan 2013
Edited by Matt J
on 27 Jan 2013

It's doubtful to me that the if statements would be a primary bottleneck. However, if it's really a concern to you, and if only the first iteration is the exception, why not execute the steps of the first iteration before the loop begins? Then just loop over the second and higher iterations which don't require any of the conditional tests.

  0 Comments

Sign in to comment.