Is there any way to access a variable whose name is expressed by another string variable?
Show older comments
Is there any way in MATLAB to access a variable whose name is expressed by another string variable?
for example, when
myvar = 10;
string_myvar = "myvar";
were in the workspace and substituting the numerical scalar myvar into another myvar2 as
myvar2 = myvar;
Id’ like to find a way to give the right hand side "as the content of string scalar ‘string_myvar’ ".
7 Comments
Why it is needed? You can striaght away initialize
string_myvar = 10 ;
Or you may go ahead with the name
myvar = 10 ;
as it is.
"Is there any way in MATLAB to access a variable whose name is expressed by another string variable?"
Yes, there are ways to do this.
But only if you want to force yourself into writing slow, inefficient, obfuscated, complex, buggy code that is hard to debug:
Daiki
on 2 Aug 2021
Stephen23
on 2 Aug 2021
@Daiki Tashiro: my pleasure! If you want more help/explanation/support, there are plenty of experienced volunteers on this forum who can help with those "alternative ways"... just ask!
Get rid of FIND: logical indexing is simpler.
The robust and efficient approach would be to put all of the variables into one container array (e.g. structure, cell array, table) and then use ISMEMBER or dynamic fieldnames or something similar to select the ones for the output.
For example:
C = {arg1,arg2,..,argN};
N = {'x1','x2',..,'xN'};
userwants = ["x1","x3"];
[X,Y] = ismember(userwants,N);
assert(all(X),'no match')
varargout = C(Y)
Daiki
on 5 Aug 2021
Answers (1)
Categories
Find more on Workspace Variables and MAT Files in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!