Matte
Matte

Reputation: 339

How to jump to a particular place in the for loop if the if condition is satisfied?

I have some image files. I'm trying to perform some calculations using each file and if a certain condition is met, I'd like to go back to a particular line in the code and run it from there once more. But only just once again. Regardless of whether the if condition is satisfied or not satisfied the second time, I want to go to the next iteration. But, MATLAB doesn't seem to have a goto function and also, using goto implies bad programming so I thought I'd just iterate the for loop twice for a particular 'i' value which satisfies the if condition.

file = dir('*.jpg');
n = length(file);
for i = 1:n
    *perform some operations on the 'i'th file*
    if 'condition'
        *run the for loop again for the 'i'th file instead of going to the 'i+1'th file*
         i=i-1;
    else
        *go to next iteration*
    end
end

I have tried to code this by changing the loop variable 'i' inside the loop to 'i-1' so that on the next iteration, the 'i'th loop will be repeated again but doing so is giving the wrong output, though I don't know if there is some other error in my code or if the changing of the loop variable internally is the cause of the problem. Any help on this is appreciated.

Upvotes: 0

Views: 1188

Answers (2)

rinkert
rinkert

Reputation: 6863

Replace the for loop with a while loop to have a bit more flexibility. The only difference is that you have to manually increment i, hence this also allows you to not increment i.

Given your new requirement, you can keep track of the number of attempts, and easily change this if needed:

file = dir('*.jpg');
n = length(file);

i = 1;
attempts = 1; 

while i <= n
    % perform code on i'th file
    success =  doSomething(); % set success true or false;

    if success
        % increment to go to next file
        i = i + 1;

    elseif ~success && attempts <= 2 % failed, but gave it only one try
        % increment number of attempts, to prevent performing 
        attempts = attempts + 1;
    else % failed, and max attempts reached, increment to go to next file
        i = i + 1;
        % reset number of attempts 
        attempts = 1;
    end
end

Upvotes: 4

Cris Luengo
Cris Luengo

Reputation: 60564

Given the new requirement, added after rinkert's answer, the simplest approach becomes separating out code from your loop in a separate function:

function main_function

  file = dir('*.jpg');
  n = length(file);
  for i = 1:n
    some_operations(i);
    if 'condition'
      some_operations(i);
    end
  end

  function some_operations(i)
    % Here you can access file(i), since this function has access to the variables defined in main_function
    *perform some operations on the 'i'th file*
  end

end % This one is important, it makes some_operations part of main_function

Upvotes: 1

Related Questions