フィルターのクリア

How to derive a variable name from a variable?

2 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2017 年 2 月 7 日
編集済み: Jan 2017 年 2 月 8 日
How to derive a variable name from a variable?
A = [5 6 7 8];
B = ‘A’;
A(1) % this works and return the first element of A which is 5
B(1) % this doesn’t work like the code above
  4 件のコメント
Rightia Rollmann
Rightia Rollmann 2017 年 2 月 7 日
What I want to do is to access the first column and then the second column of a 5-by-7 matrix which is the value of a field named B. B is the third field of struct A. How can I do it dynamically best?
Adam
Adam 2017 年 2 月 8 日
If B is a field of A why are you trying to create a variable B that represents the whole of A.
Just A.( 'B' ) would give what you want. Fields are not really ordered in a struct, at least not for general usage.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2017 年 2 月 7 日
編集済み: Stephen23 2017 年 2 月 7 日
Although often loved by beginners, dynamically accessing variable names is not a robust, fast, or good way to write code. It makes code hard to read, slow, difficult to debug, and has other disadvantages too:
If you really need to access the names dynamically, then consider using a structure: it is fast and easy to access structure field names dynamically:
S.A = [5,6,7,8];
x = 'A';
S.(x)

その他の回答 (2 件)

Star Strider
Star Strider 2017 年 2 月 7 日
MATLAB does not recognise char(0145) and char(0146) as quotation marks in code.
A = [5 6 7 8];
B = 'A' % Sets ‘B’ TO Be Character ‘A’
B = A
B(1)
produces:
B =
A
B =
5 6 7 8
ans =
5

Jan
Jan 2017 年 2 月 8 日
編集済み: Jan 2017 年 2 月 8 日
According to your comment, which is another problem than the original question:
A.B(:, 1:2)

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by