Borrar filtros
Borrar filtros

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

57 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

Stephen23
Stephen23 el 24 de Abr. de 2018
Editada: Stephen23 el 24 de Abr. de 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?:

Más respuestas (1)

Fangjun Jiang
Fangjun Jiang el 24 de Abr. de 2018
Editada: Fangjun Jiang el 24 de Abr. de 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 comentario
Stephen23
Stephen23 el 24 de Abr. de 2018
Editada: Stephen23 el 24 de Abr. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by