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

19 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Stephen23
Stephen23 il 24 Apr 2018
Modificato: Stephen23 il 24 Apr 2018
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?:

Più risposte (1)

Fangjun Jiang
Fangjun Jiang il 24 Apr 2018
Modificato: Fangjun Jiang il 24 Apr 2018
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 Commento
Stephen23
Stephen23 il 24 Apr 2018
Modificato: Stephen23 il 24 Apr 2018

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.

Accedi per commentare.

Community Treasure Hunt

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

Start Hunting!

Translated by