How can i use a "list of variablennames" to calculate something?

조회 수: 12 (최근 30일)
Robert Rüssel
Robert Rüssel 2022년 6월 24일
답변: Jeff Miller 2022년 6월 24일
Dear Community,
I have a list that contains all the variables. This list is a 1xn cellarray. Now I want to take a variable name and calculate with it (the list only contains the name of a variable that can also be found in my workspace). I think its a problem with dataformat... but which dataformat can help to solve my problem?
Example:
% Example
a = [1, 2, 3; 4, 5, 6]
b = [1, 2, 3; 4, 5, 6] % This is my variable. I dont know the name of this variable. But i find my variable through the list of Variablenames
c = char(Variableformlist(1,1)) % char(Variableformlist(1,1)) = b
d = c./a % that doesnt work
% Next Try:
d = char(Variableformlist(1,1)) ./ a % that doestnt work also
% Next Try:
d = Variableformlist(1,1) ./ a % that doestnt work also
Thank you for your help!
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2022년 6월 24일
@Robert Rüssel - perhaps you need to show how the Variableformlist is created...it sounds like it is initialized with the variable names rather than the variable data...is that correct? If so, then why don't you just store the variable data in the cell array instead? What are you hoping to achieve by storing variable names in the cell array?
Stephen23
Stephen23 2022년 6월 24일
편집: Stephen23 2022년 6월 24일
"I think its a problem with dataformat"
It is a problem of poor data design.
"but which dataformat can help to solve my problem?"
The simple and effiicient MATLAB approach: array + indexing.

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

답변 (2개)

Steven Lord
Steven Lord 2022년 6월 24일
I have a list that contains all the variables.
The approach you described smells a bit bad.
Can you dynamically create or reference variables, including some with numbered names like x1, x2, x3, etc.? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches.

Jeff Miller
Jeff Miller 2022년 6월 24일
One convenient option if you really want to do something like this is to use a structure to hold all of the variables that you want to reference by name, and then you can reference them by name. E.g.
% Example
a = [1, 2, 3; 4, 5, 6]
mynamedvars.b = [1, 2, 3; 4, 5, 6]; % This is my variable. I dont know the name of this variable. But i find my variable through the list of Variablenames
c = char(Variableformlist(1,1)) % char(Variableformlist(1,1)) = b
d = mynamedvars.(c)./a % this works if c is now the string 'b'

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by