MATLAB Answers

How do I use a user input string to reference a structure that already exists?

조회 수: 14(최근 30일)
JT
JT 2021년 9월 17일
댓글: JT 2021년 9월 21일 17:00
I want the user to input a string and then I want to use that name to reference an existing structure so that I can redefine a field in another existing structure.
Example-
UserInput='ExistingStructure'
ExistingStructure.VariableName.Value=DifferentStructure.VariableName.Value
Is there a simple method for doing this?
  댓글 수: 4
Stephen
Stephen 2021년 9월 20일 14:50
"I could ask users to hard code their individual structures but some may not have high levels of matlab ability. It's better if they can just define their structure name."
I doubt that, that sounds like a very fragile, inefficient, buggy way to write code.
A much more robust approach is to let your users simply call a function with whatever input arrays they want.
"Maybe this is impossible?"
Why do you think that? The page that I linked to gives links to many examples of how you could do this.

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2021년 9월 20일 13:14
I have multiple users with different structure names that need to use this. I want them to be able to input their structure name into the string and then just have it work.
Rather than trusting your users not to enter an invalid structure name that is instead malicious code (the Bobby Tables problem) I would write a function for your users to call. They can call your function with a struct with whatever name they want, but inside your function you refer to that struct with a fixed name.
myLongStructName = struct('x', 1, 'y', 2); % User's choice of name
z = myfun(myLongStructName)
z = 5
% The q defined out here doesn't interfere with the q in myfun
q = struct('x', 3, 'y', 4);
answer = myfun(q)
answer = 19
function q = myfun(s) % Your choice of name
q = s.x + s.y.^2;
end

추가 답변(1개)

Chunru
Chunru 2021년 9월 18일
Here is one solution without dynamically naming a variable:
...
UserInput='ExistingStructure';
if exist(userInput, 'var')
ExistingStructure.VariableName.Value=DifferentStructure.VariableName.Value;
else
disp("The variable " + userInput + "doesn't exist");
end
  댓글 수: 2
Stephen
Stephen 2021년 9월 20일 14:46
"I don't want to hard code it in. I have multiple users with different structure names that need to use this. I want them to be able to input their structure name into the string and then just have it work."
How do all of these users get these many structures into one workspace at once: twenty people using one PC?
I doubt that you do that... so most likely at some point you have to import the users' data, and that would be the suitable and easy place to handle this better.
"In short, I appreciate your efforts but the dynamic definition is the fundemental goal of this question."
This even has a name:

댓글을 달려면 로그인하십시오.

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by