필터 지우기
필터 지우기

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

조회 수: 57 (최근 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 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