How can I make struct with existing variables?
조회 수: 109 (최근 30일)
이전 댓글 표시
채택된 답변
Matt J
2014년 8월 22일
편집: Matt J
2014년 8월 22일
>> clear
>> a=1; b=2; c=3;
>> s=whos;
>> C=cell2struct({s.name}.',{s.name})
C =
a: 'a'
b: 'b'
c: 'c'
>> structvars(C,0); %copy/paste the output below to the command line
ans =
C.a = a;
C.b = b;
C.c = c;
추가 답변 (3개)
Guillaume
2014년 8월 22일
s = struct('alpha', alpha, 'beta', beta, 'gamma', gamma);
doc struct
댓글 수: 2
Guillaume
2014년 8월 22일
You could dynamically create a structure with 30 field names that are the names of the variables, however I would urge to think whether it's really what you want. How are you going to then use that structure if the field names are created arbitrarily. I would advise against this as your code may easily break in the future because a hardcoded field is not there anymore.
If that's really what you want to do, then structvars from the other answer (you have to download it), or the following function will do it:
function s = variables2struct(varargin)
s = struct;
for var = 1:nargin
s.(genvarname(inputname(var), fieldnames(s))) = varargin{var};
end
end
Adam
2014년 8월 22일
편집: Adam
2014년 8월 22일
myStruct.alfa = alfa;
myStruct.beta = beta;
etc.
Or
myStruct = struct( 'alfa', alfa, 'beta', beta );
댓글 수: 4
Adam
2014년 8월 22일
I could try to give some help further along this line, but I think potentially either of Matt J's solutions would work better so unless neither of them do I'll leave it.
참고 항목
카테고리
Help Center 및 File Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!