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

11 ビュー (過去 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 Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by