conversion

조회 수: 3 (최근 30일)
Baba
Baba 2011년 11월 16일
i have a struct loaded and one of it's fields contains names such that struct(1).name contains "First" struct(2).name containis "Second" and so on
I would like to use these struct fields as a variable in my code. For example I'd like to set struct(1).name=content of some matrix so instead of saying X=[1;2;3] i'd like to say struct(1).name=[1,2,34] so First=[1,2,34] would be stored in the workspace. I just don't know how i need to convert struct(i).name to be able to use it
  댓글 수: 1
Baba
Baba 2011년 11월 16일
i think i was looking for varname = genvarname(struct(1).name)

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

답변 (2개)

Jan
Jan 2011년 11월 16일
Creating variables dynamically is prone to errors, hard to debug and slows down Matlab. Therefore it is recommended to avoid this.
A more efficient approach is using dynamic fieldnames:
data.(struct(1).name) = [1, 2, 34];
data.(struct(2).name) = [1, 2, 34];
Then the new variables are encapsulated in the struct data.
  댓글 수: 1
Jonathan
Jonathan 2011년 11월 16일
I agree.

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


Jonathan
Jonathan 2011년 11월 16일
Baba,
This will do what you described.
structVar(1).name = 'First';
structVar(2).name = 'Second';
makeVarFun = @(str, val) assignin('caller', genvarname(str), val);
for i = 1:numel(structVar)
varName = structVar(i).name;
makeVarFun(varName, i);
end

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by