help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Looping over two equal length cell arrays?


From: David Bateman
Subject: Re: Looping over two equal length cell arrays?
Date: Sat, 01 May 2010 02:21:43 +0200
User-agent: Mozilla-Thunderbird 2.0.0.22 (X11/20090706)

Søren Hauberg wrote:
fre, 30 04 2010 kl. 22:54 +0000, skrev fork:
This is what I want to do:

s = struct()
keys = {'a', 'b', 'c'}
vals = {1,2,3}
for k = keys, v = vals
    s = setfield(s, k, v);
endfor
s.a == 1

I'm not sure if this syntax is nicer, but here it goes anyway:

        keys = {'a', 'b', 'c'};
        vals = {1, 2, 3};
        va = cell (1, 2*numel (keys));
        va (1:2:end) = keys;
        va (2:2:end) = vals;
        s = struct (va {:});

You can simplify that to

keys = {'a', 'b', 'c'};
vals = {1, 2, 3};
s = struct ([keys; vals]{:});

though if you are unsure of the orientation of the cell arrays the last line might need to be

s = struct ([keys(:)'; vals(:)']{:});


D.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]