Rand
Rand

Reputation: 31

Passing multiple inputs into a MATLAB function via loop?

I have multiple variables var_1, var_2, var_3....var_9 (they are named like that) that I want to pass in a function. All of the variables are saved in the workspace. The function takes 2 variables, and spits out an output. I want to compare var_1 with all the variables, including itself, so I prefer to automate it in a loop.

So I want to execute

function(var_1,var_1)--> display answer, function(var_1,var_2)--> display answer...function(var_1,var_9)-->display answer all at once in a loop. I've tried the following, with no luck:

for i=1:7
functionname(var_1,var_'num2str(i)')
end

Where did I go wrong?

Upvotes: 1

Views: 836

Answers (1)

Matt
Matt

Reputation: 13923

You cannot make a dynamic variable name directly. But you can use the eval-function to evaluate an expression as a string. The string can be generated with sprintf and replaces %d with your value.

for i=1:7
  eval(sprintf('functionname(var_1,var_%d)', i));
end

But: Whenever you can, you should avoid using the eval function. A much better solution is to use a cell array for this purpose. In the documentation of Matlab there is a whole article about the why and possible alternatives. To make it short, here is the code that uses a cell array:

arr = {val_1, val_2, val_3, val_4, val_5, val_6, val_7, val_8, val_9};

for i = 1:length(arr)
  functionname(arr{1},arr{i})
end

Upvotes: 4

Related Questions