How can I convert a string which contains a variable name into a variable which can be called?
1 回表示 (過去 30 日間)
古いコメントを表示
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?
Thanks in advance, Ak
2 件のコメント
Jan
2018 年 4 月 26 日
This means, that you are trying to create a Matlab interpreter. Are you sure that this meta-programming is useful? Matlab is a perfect Matlab interpreter already. So what about using the debugger?
Stephen23
2018 年 4 月 26 日
"I am trying to convert these strings, which contain pre-established variables, into variables which can be called. Any suggestions?"
The best suggestion is Do NOT do this. Dynamically accessing variable names uis slow, complex, and buggy. Dynamically accessing variable names is how beginners force themselves into writing slow, complex code that they struggle to debug. Read this to know why:
There are easier ways to achieve what you want: fields of a structure, table variables, indexing, etc. All of these will be simpler, neater, and much more efficient.
採用された回答
Walter Roberson
2018 年 4 月 26 日
You do not need to do that.
Put all of the variables into a structure, using dynamic field names. Then when you need to recall them by name,
Variables_for_this_call = cellfun(@(name) StructureOfVariables.(name), ListOfNames, 'uniform', 0);
After which you can
DummyFunction(Variables_for_this_call{:})
2 件のコメント
Stephen23
2018 年 4 月 27 日
編集済み: Stephen23
2018 年 4 月 27 日
" Could you please 'dumb-it-down' a little bit?Í"
Sure.
"...I need a way of converting the string "handles.x" ... into a variable..."
fnm = 'x';
data = handles.(fnm);
That is our advice in a nutshell. Read the link I gave in my comment to know more about why your code concept will force you into writing slow, complex, buggy code.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!