1

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?

1

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

@nkjt: I edited my answer and proposed the better approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.