Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
Robert Rüssel
Robert Rüssel el 24 de Jun. de 2022
Respondida: Jeff Miller el 24 de Jun. de 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 comentarios
Geoff Hayes
Geoff Hayes el 24 de Jun. de 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 el 24 de Jun. de 2022
Editada: Stephen23 el 24 de Jun. de 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.

Iniciar sesión para comentar.

Respuestas (2)

Steven Lord
Steven Lord el 24 de Jun. de 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 el 24 de Jun. de 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'

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by