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

57 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by