2
votes

So I have a for-loop in MATLAB, where either a vector x will be put through one function, say, cos(x).^2, or a different choice, say, sin(x).^2 + 9.*x. The user will select which of those functions he wants to use before the for-loop.

My question is, I dont want the loop to check what the user selected on every iteration. Is there a way to use a pointer to a function, (user defined, or otherwise), that every iteration will use automatically?

This is inside a script by the way, not a function.

Thanks

2

2 Answers

4
votes

You can use function_handles. For your example (to run on all available functions using a loop):

x = 1:10; % list of input values
functionList = {@(x) cos(x).^2, @(x) sin(x).^2 + 9*x}; % function handle cell-array
for i=1:length(functionList)
    functionOut{i} = functionList{i}(x); % output of each function to x
end
2
votes

You can try something like the following:

userChoice = 2;

switch userChoice
    case 1
        myFun = @(x) sin(x).^2 + 9.*x;
    case 2
        myFun = @(x) cos(x).^2;
end

for k = 1:10
    x(k,:) = myFun(rand(1,10));
end