Using assignin with array indexing
9 views (last 30 days)
Show older comments
Hello everyone,
I am facing a problem using MATLABs assignin() function. First of all I have heard that it is not recommended by many users to use assignin. However, I think in this case it might be necessary.
What I need to do is read variable names as well as the corresponding values from an EXCEL user interface. The variable names are stored in cel array called "v", the values in cell array called "values". At the moment I am using the following code that works without any problems:
v = {'variableName1','variableName2'};
values = {10,20};
for n = 1:numel(v)
assignin('base',char(v(n)),values{n})
end
The problem is that some variables I want to assign values in are no single values but part of an array. For instance I might want to assign values in the variables "variableName1" and also in the second position of "variableName2". I tried to use the following code but it creates an error as "variableName2(2)" is not a valid variable name.
v = {'variableName1','variableName2(2)'};
values = {10,20};
for n = 1:numel(v)
assignin('base',char(v(n)),values{n})
end
Is there a way to fix this error?
3 Comments
Stephen23
on 8 Mar 2019
"This flexibility is required and in my knowledge (I might be wrong here) I need assignin or evalin to realize it."
Nothing in code is "required", you always have a choice in how to approach a task. In this case you designed your data in such a way that you painted yourself into that corner: by using lots of separate variables you force yourself into writing slow, complex, buggy code. So without realizing you beg the question: "if I have lots of separate variables (which can be accessed only using slow and complex code), how can I access them?" Answer: using slow and complex code.
"I did not want to assume that using one of those "bad" functions is the only way to solve my problem."
You could trivially get the same flexibilty using a structure or a table, neither of which require magically accessing variable names: they would be more robust, easier to manage, easier to debug, and likely much more efficient:
Interfering in other workspaces is also inefficient, hard to debug, and is best avoided. The best way to pass data from one workspace to another is to pass it as input/output arguments.
Accepted Answer
Fangjun Jiang
on 8 Mar 2019
prepare the full assignment statement and use evalin().
3 Comments
Fangjun Jiang
on 8 Mar 2019
v = {'variableName1','variableName2(2)'};
values = {10,20};
for n = 1:numel(v)
statement=sprintf('%s=%d;',v{n},values{n});
evalin('base',statement)
end
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!