How to generate variable names from a cell array

조회 수: 93 (최근 30일)
Matt C
Matt C 2016년 9월 6일
편집: Stephen23 2019년 6월 19일
Hello, all. This is an instance where plenty of documentation exists, yet I am still having trouble interpreting it for my purposes.
If I have an cell array of the following form:
CellArray = {
'variable1' 'hello';
'variable2' 'world';
'variable3' 3.14159;
'variable4' [42 24]
};
How does one generate variables in the MATLAB workspace, so that:
variable1 = 'hello'
variable2 = 'world'
variable3 = 3.14159
variable4 = [42 24]
The second column of the cell array might be other types of variables as well (i.e. CellArray{1,2} might be numerical instead of a string, depending on my usage task).
Also note that the older genvarname() function will be removed in upcoming releases of Matlab, and the documentation says to use MATLAB.LANG.MAKEVALIDNAME and MATLAB.LANG.MAKEUNIQUESTRINGS instead.
If you anyone could propose a snippet of code that would be able to do this for me, it would be greatly appreciated. Thanks!
  댓글 수: 1
Stephen23
Stephen23 2016년 9월 6일
편집: Stephen23 2016년 9월 6일
Just use a structure: this would be much simpler and more reliable than any hack code you could write that creates those variables names dynamically.
>> C = {
'variable1' 'hello';
'variable2' 'world';
'variable3' 3.14159;
'variable4' [42 24]
};
>> Ct = C';
>> S = struct(Ct{:});
>> S.variable1
ans = hello
>> S.variable4
ans =
42 24

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2016년 9월 6일
편집: Stephen23 2019년 6월 19일
  댓글 수: 2
Matt C
Matt C 2016년 9월 8일
I guess my initial argument was "ya, I know this a bad idea but I want to do it anyway". Judging by the amount of published material on why its not a good idea, I guess I'll just have to accept that my code shouldn't contain dynamically-created variables after all...
Thanks
Walter Roberson
Walter Roberson 2016년 9월 8일
A structure would probably work well for you.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 9월 6일

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by