Inline Indexing to Dynamic Field Names

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,

 Akzeptierte Antwort

Oleg Komarov
Oleg Komarov am 8 Sep. 2011

0 Stimmen

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 Kommentar

Sean
Sean am 28 Sep. 2011
Thanks Oleg... I had developed my own way of doing this with a custom indexer function, but I much prefer to do it with inbuilt matlab functionality than having extraneous personal functions involved.
The method I used was to add a function equivalent to:
function x=indexer(y,n)
x=y(n);
that I used like:
TestStruct.Varnames{indexer(fun(x),n)} = 0;

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Chaowei Chen
Chaowei Chen am 31 Aug. 2011

1 Stimme

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 Kommentare

Paulo Silva
Paulo Silva am 31 Aug. 2011
+1 vote
Sean
Sean am 31 Aug. 2011
I'm sorry... maybe I wasn't clear enought in my request.
"TestStruct.(Varnames{1,3}) = 0" works if I can get the relevant value. But if y=fun(x) returns something of the form [5 7 2 6] then I have passed an array to Varnames() instead of the desired value when I write:
TestStruct.(Varnames(fun(x)))=0
How can I (inline) tell it I am only interested in the value at a particular index (for example index 3)?
Thanks
Jan
Jan am 8 Sep. 2011
@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
Walter Roberson am 8 Sep. 2011
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by