フィルターのクリア

Is there any way to convert variables from list to arrays?

67 ビュー (過去 30 日間)
Abhay SAMUDRASOK
Abhay SAMUDRASOK 2018 年 4 月 24 日
コメント済み: Stephen23 2018 年 4 月 24 日
I have 2 arrays
a = [1 2 3]
b = [2 3 4]
and a list
c = {'a', 'b'}
when I use cell2mat(c(1,1)), I get a, but what I want is [1 2 3]. Is there any way to achieve it?

採用された回答

Stephen23
Stephen23 2018 年 4 月 24 日
編集済み: Stephen23 2018 年 4 月 24 日
Simply store the data in one structure, and then it is trivially easy (no slow, buggy eval is required):
>> S.a = [1,2,3];
>> S.b = [2,3,4];
>> C = {'a','b'};
>> S.(C{1})
ans =
1 2 3
Simpler code through better code design: faster, neater, simpler, more efficient, easiest to debug, less complex. Why waste your time learning bad ways to write code?:

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2018 年 4 月 24 日
編集済み: Fangjun Jiang 2018 年 4 月 24 日
a=1:3;
b=2:4;
c={'a','b'};
you could do
d=eval(c{1})
or, you should do
clear c;
c.a=a;
c.b=b;
MyVar='a';
c.(MyVar)
  1 件のコメント
Stephen23
Stephen23 2018 年 4 月 24 日
編集済み: Stephen23 2018 年 4 月 24 日

Do NOT use eval for trivial code like this. The MATLAB documentation specifically recommends against doing what this answer shows: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."

Source: https://www.mathworks.com/help/matlab/matlab_prog/string-evaluation.html

Using eval is how beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read more here:

https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval

See my answer for a simple solution that avoids these problems entirely.

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

カテゴリ

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