0

I am creating a function which scans files for a certain function and determines which variables (all are already initialized) are used as parameters for the function. Currently, I am able to derive a cell array with strings for each individual variable. The program takes this:

x = DummyFunction(a, b, c);

And returns this:

{'a'} {'b'} {'c'}

I am trying to convert these strings, which contain pre-established variables, into variables which can be called. Any suggestions?

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
Ak K
  • 1
  • 1

2 Answers2

3

The function you're looking for is matlab.lang.makeValidName (introduced in R2014a):

N = matlab.lang.makeValidName(S) constructs valid MATLAB® identifiers, N, from input strings, S. The makeValidName function does not guarantee the strings in N are unique.

A valid MATLAB identifier is a character vector of alphanumerics (A–Z, a–z, 0–9) and underscores, such that the first character is a letter and the length of the character vector is less than or equal to namelengthmax.

makeValidName deletes any whitespace characters before replacing any characters that are not alphanumerics or underscores. If a whitespace character is followed by a lowercase letter, makeValidName converts the letter to the corresponding uppercase character.

So for example:

>> matlab.lang.makeValidName(["_privateField", "some name"])

yields:

ans = 

  1×2 string array

    "x_privateField"    "someName"

I am not sure it applies to your use case, but you might want to look at: Why Variables Should Not Be Named Dynamically (eval).

Perhaps what you really want to do is check whether variables with certain names exist, then do something accordingly - in which case you could use the exist function:

tf = exist('varName','var')

So for example:

if exist('a','var') && exist('b','var')
  res = someFunction(a,b);
else
  res = someFunction(default_a,default_b);
end
Community
  • 1
  • 1
Dev-iL
  • 23,742
  • 7
  • 57
  • 99
1

Try storing your variables in a structure and use dynamic field referencing. Here is an example:

variables.a = 1;
variables.b = 2;
variables.c = 3;

% scan your file here
% let's assume a and b are found in the file
variables_present = ['a', 'c'];

for i = 1:length(variables_present)
    % use dynamic field reference
    disp(variables.(variables_present(i)))
end

This will produce the output:

1
3

Follow this link for more information on how to use dynamic field referencing:

jgrant
  • 1,273
  • 1
  • 14
  • 22