使用结构作为向量的索引

Use struct as index into vector

是否有"better"(意味着可读和矢量化)方法来使用带有索引的结构来生成结果结构?

# struct values are indices into b
a.foo = 2;
a.bar = 3;

b = [e pi 123 1337];

## the loopy way
for [val, key] = a
  c.(key) = b(val);
endfor

disp (c)

给出了想要的结果

scalar structure containing the fields:

  foo =  3.1416
  bar =  123

或另一种笨拙且几乎令人困惑的方式:

d = cell2struct(num2cell(b([struct2cell(a){:}])'), fieldnames(a));
assert (c, d);

理论上,您要寻找的可爱单线可能是:

structfun (@ (x) b(x), a, 'UniformOutput', false);

然而,与其他 'fun' 亲戚一样,structfun 似乎只是语法糖,而不是实际的矢量化。所以实际上最快(也可以说是最干净)的方法似乎是你的 for 循环:

基准:

octave:1>  a.foo = 2; a.bar = 3; b = [e pi 123 1337];

octave:2>  # loop method #
        >  tic; for i = 1 : 100; 
        >    for [val, key] = a; S1.(key) = b(val); end; 
        >  end; toc
Elapsed time is 0.00160003 seconds.

octave:3>  # cell2struct method # 
        >  tic; for i = 1 : 100; 
        >    S2 = cell2struct(num2cell(b([struct2cell(a){:}])'), fieldnames(a));
        >  end; toc
Elapsed time is 0.006423 seconds.

octave:4>  # structfun method #
        >  tic; for i = 1: 100
        >    S3 = structfun(@ (x) b(x), a, 'UniformOutput', false);
        >  end; toc
Elapsed time is 0.279853 seconds.

PS。但是,请注意,如果你有一个 array 的结构,而 structfun 方法会。