Search code examples
matlabfor-loopcontinue

Alternative for continue function in a function (matlab)


We cannot use continue function in functions in matlab. For example, the following is not allowed:

for ii = 1:5  
    function1(ii)  
end  

function function1(in)  
   if ii, continue; else, disp('hi'); end  
end

Is there an alternative structure I should be using? Should I always just put the for loop inside the function? Would there be a reason not to put for loop inside the function?


@Peng Chen answers most of my answers. Yet, I wanted to add that the simple solution for MATLAB-specific problem was to use 'return' instead of 'continue' in the subfunction.


Solution

    1. Yes. For example:

      for ii = 1:5
          out=function1(ii);
          if out,continue;end
      end  
      
      function out=function1(in)
          if in,out=1;else,out=0;disp('hi');end
      end
      

      Let the function1 deal with ii. Use return value of function1 to deal with the for loop.

    2. No.
    3. When you need to use A (a variable outside function1, maybe a global variable) in the for loop, you should pass A to function1. Passing argument or particular declaration is bother.
    4. When function1 is called, MATLAB exit the main program and go into function1. So "continue" can not skip the for loop. By the way, there is no ii inside function1, only in.

    Sorry for my poor English.