MATLAB: How to position flexibly the start of a for cycle

cyclefor

My code is something like this:
expressions_1
expressions_2
expressions_3
I need a for cycle, but the start of the cycle depends on a parameter. So I would like that my code behave like this in case of param = 1:
for i=1:N
expressions_1
expressions_2
expressions_3
end
but for param = 2 it should be:
expressions_1
for i=1:N
expressions_2
expressions_3
end
How to do this in general?

Best Answer

  • The proper way of doing this would be to have each expression in its own function (if it's simple enough anonymous functions would do) and dispatch to the functions as required, e.g.:
    function flexibleexpression(x, N)
    expressions = {
    @(x) x+1;
    @(x) 2*x;
    @(x) sin(x);
    @(x) expression4(x); %expression4 is a function defined separately
    };
    x = pi;
    for expr = 1 : paramater_value-1
    %execute expressions before the loop
    x = expressions{expr}(x);
    end
    %now perform the loop
    for i = 1:N
    for expr = parameter_value : numel(expressions)
    x = expressions{expr}(x);
    end
    end
    end
    function x = expression4(x)
    if x < 0
    x = [x 1];
    else
    x = [x -1];
    end
    end
    A dirty way of doing it would be to replace the anonymous functions by strings and eval those in the expr loop.