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

11 Ansichten (letzte 30 Tage)
Robert Rüssel
Robert Rüssel am 24 Jun. 2022
Beantwortet: Jeff Miller am 24 Jun. 2022
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 Kommentare
Geoff Hayes
Geoff Hayes am 24 Jun. 2022
@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 am 24 Jun. 2022
Bearbeitet: Stephen23 am 24 Jun. 2022
"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.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Steven Lord
Steven Lord am 24 Jun. 2022
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 am 24 Jun. 2022
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'

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by