Using assignin with array indexing
조회 수: 7 (최근 30일)
이전 댓글 표시
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
Stephen23
2019년 3월 8일
"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.
채택된 답변
Fangjun Jiang
2019년 3월 8일
prepare the full assignment statement and use evalin().
댓글 수: 3
Fangjun Jiang
2019년 3월 8일
v = {'variableName1','variableName2(2)'};
values = {10,20};
for n = 1:numel(v)
statement=sprintf('%s=%d;',v{n},values{n});
evalin('base',statement)
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!