1

How to declare dynamic variable names in Matlab, and the function returns those variables? I want the function that returns the string with dynamic variable name and returns only when number of iterations n is given.

I have tried the my following code:

    function [var] = myFunc(n)

    for ii=1:n
              var= ['var' num2str(ii)];
              var{ii} = strcat('(some srting', var,')');
              eval(['var' num2str(ii) ' = var']);
    end
    end

1 Answers1

0

CASE 1: This will get you the eval strings that you can use later on to actually get values into var1, var2, var3, etc. from some variables named some_string_1, some_string_2, some_string_3 respectively.

function varargout = myFunc1(n)

for ii=1:n
    eval_string = strcat('var',num2str(ii),'=','some_string_',num2str(ii));
    varargout(ii) = {eval_string};
end
return;

Sample runs:

  • Two outputs from 5 possible ones

    [v1,v2] = myFunc1(5)

    v1 =

    var1=some_string_1

    v2 =

    var2=some_string_2

  • Four outputs from 5 possible ones

    [v1,v2,v3,v4] = myFunc1(5)

    v1 =

    var1=some_string_1

    v2 =

    var2=some_string_2

    v3 =

    var3=some_string_3

    v4 =

    var4=some_string_4

Another solution to this case could be to get the strings in a cell array -

function eval_strings_cell = myFunc1_1(n)

for ii=1:n
    eval_strings_cell(ii) = {strcat('var',num2str(ii),'=','some_string_',num2str(ii))};
end
return;

Sample run:

  • Three outputs

    [var] = myFunc1_1(3)

    var =

    'var1=some_string_1'    'var2=some_string_2'    'var3=some_string_3'
    

CASE 2: If you wish to evaluate values for var1, var2, var3, etc. you need to pass values to be assigned to it through the input arguments of the function, because functions can't just pick variables from the workspace.

So, for that case, you may use this -

function varargout = myFunc2(n,some_string_1,some_string_2,some_string_3)

for ii=1:n
    eval_string = strcat('varargout(',num2str(ii),')=','{some_string_',num2str(ii),'}');
    evalc(eval_string);
end
return;

Sample runs:

  • Pick values from first two inputs only -

    [v1,v2] = myFunc2(2,10,12,13)

    v1 =

    10
    

    v2 =

    12
    
  • Pick values from all three inputs -

    [v1,v2,v3] = myFunc2(3,10,12,13)

    v1 =

    10
    

    v2 =

    12
    

    v3 =

    13
    

CASE 3: If you were looking for something like the above case, you don't need eval. You can just directly get the values into varargout, as shown here -

function varargout = myFunc3(n,varargin)

for ii=1:n
    varargout(ii) = varargin(ii);
end
return;

Sample runs:

  • Three inputs, two outputs -

    [v1,v2] = myFunc3(2,10,12,13)

    v1 =

    10
    

    v2 =

    12
    
  • Three inputs, three outputs

    [v1,v2,v3] = myFunc3(3,10,12,13)

    v1 =

    10
    

    v2 =

    12
    

    v3 =

    13
    
Divakar
  • 218,885
  • 19
  • 262
  • 358