Most efficient way to loop through an Eigen matrix

后端 未结 4 1314
栀梦
栀梦 2021-02-02 01:37

I\'m creating some functions to do things like the \"separated sum\" of negative and positive number, kahan, pairwise and other stuff where it doesn\'t matter the order I take t

4条回答
  •  自闭症患者
    2021-02-02 02:08

    I notice that the code is equivalent to the sum of all the entries in the matrix, i.e., you could just do this:

    return xs.sum();
    

    I would assume that would perform better since it's only a single pass, and furthermore Eigen ought to "know" how to arrange the passes for optimum performance.

    If, however, you want to retain the two passes, you could express this using the coefficient-wise reduction mechanisms, like this:

    return (xs.array() > 0).select(xs, 0).sum() +
           (xs.array() < 0).select(xs, 0).sum();
    

    which uses the boolean coefficient-wise select to pick the positive and negative entries. I don't know whether it would outperform the hand-rolled loops, but in theory coding it this way allows Eigen (and the compiler) to know more about your intention, and possibly improve the results.

提交回复
热议问题