naming a structure
조회 수: 4 (최근 30일)
이전 댓글 표시
clear all
FName = {'Data1','Data2','Data3'};
data1 = [rand(32,1),rand(32,1),rand(32,1)];
NewName = {'Location1'};
Location1 = struct('Data1',data1)
From this example how is it possible to adapt the script so that instead of typing 'Location1' as the name of the structure, can that be defined from 'NewName' i.e. defining the name of the structure from a pre-defined string?
댓글 수: 0
채택된 답변
Kevin Holst
2012년 2월 22일
You can use eval, but eval needs to be used with extreme care. You can really screw things up accidentally.
eval([NewName ' = struct(''Data1'',data1);'])
If somehow your string is a command like 'clear all' or worse then that command will be run, so use eval sparingly. If there's a possibility of that happening then you might want to put a check in there.
댓글 수: 1
Jan
2012년 2월 23일
Creating variables dynamically has two big disadvantages: 1. The debugging is very hard, because you cannot see in the code, where the value is defined. 2. Inserting a variable to the internal lookup-table of variables is slow, while variables, which are defined explicitely in the code are handled much faster, e.g. by the JIT-acceleration.
추가 답변 (1개)
Walter Roberson
2012년 2월 22일
댓글 수: 4
Kevin Holst
2012년 2월 23일
I like this approach, and will be suggesting it in the future. Much safer, clearer, and cleaner.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!