Inline Indexing to Dynamic Field Names
조회 수: 2 (최근 30일)
이전 댓글 표시
How can I integrate and index function output into dynamic field names?
Example:
Say function y=fun(x) outputs an array of integers.
How can I implement:
Varnames=['var1' 'var2' 'varx' 'vary'];
TestStruct.(Varnames(index(fun(x),3))) = 0;
that is equivalent to: (for instance)
TestStruct.varx = 0;
or better yet, if varx is an array, a way to make it equivalent to:
TestStruct.varx(n) = 0;
Is there a way to tell a function that you are only interested int the nth element?
Thanks in advance,
댓글 수: 0
채택된 답변
Oleg Komarov
2011년 9월 8일
I felt Walter was a challenge, I shouldn't be suggesting stuff like this...
Varnames = {'var1', 'var2', 'varx', 'vary'};
x = [2 4 1 3];
n = 3;
TestStruct.(Varnames{x*accumarray(n,1,[numel(x),1])}) = 0
or better
s = struct('type','()','subs',{{n}});
TestStruct.(Varnames{subsref(x,s)}) = 0
추가 답변 (1개)
Chaowei Chen
2011년 8월 31일
Varnames={'var1', 'var2', 'varx', 'vary'};
%if varx is scalar
TestStruct.(Varnames{1,3}) = 0
%if varx is array
TestStruct=struct(Varnames{1,3},zeros(10,1))
댓글 수: 4
Jan
2011년 9월 8일
@Sean: You can't. Do not waste time with searching for an inline version. Simply use a FOR loop to access a list of fields.
Walter Roberson
2011년 9월 8일
Well, you can. But it is ugly and obscure and would have even experienced MATLAB programmers trying to figure out what is going on. A simple loop would be shorter, faster, and much much clearer.
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!