7

How do you put corresponding values from different lists together according to some operation?

E.g. I have three lists giving the velocity in the x, y and z direction respectively. I'd like create one list giving the 2-norm, $\sqrt{x^2+y^2+z^2}$.

I would be able to do it procedurally by using for example MapIndexed on one of the lists toghether with Part, I suppose. But I'd like to know if there is a more elegant solution.

C. E.
  • 70,533
  • 6
  • 140
  • 264

2 Answers2

10

The general way to do this is using MapThread. Using your norm example,

MapThread[Norm[{##}]&, {listX, listY, listZ}]

This particular example has easier solutions though:

Sqrt[ listX^2 + listY^2 + listZ^2 ]
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
4

Map on the Transposed list seems to be faster than MapThread

Map[Norm,Transpose@{listX, listY, listZ}]

but not nearly as fast as Szabolcs's second suggestion Sqrt[listX^2+listY^2+ listZ^2].

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
kglr
  • 394,356
  • 18
  • 477
  • 896
  • Your method Norm/@ Transpose@{X, Y, Z} is faster than Szabolcs' firt one, and more general than his second one, since you can use e.g. Norm[#,p]& where p is a real number >=1, however in this case not much faster than the first one. – Artes Mar 17 '12 at 16:47
  • @Artes, good observation. Didn't think about other norms, but noticed that Norm[#,2]& and Norm gave roughly the same timings. More interestingly, Total[{X,Y,Z}] is about 10X faster than Norm[#,1]&/@Transpose@{X,Y,Z}] (roughly same improvement in the Sqrt[X^2+Y^2+Z^2] versus Norm/@Transpose@{X,Y,Z} comparison.) – kglr Mar 18 '12 at 01:38
  • Norm[#,2]& and Norm are equivalent, so it's not surprising they give the same timings, while Norm[#,1]&/@Transpose@{X,Y,Z}] and Total[{X,Y,Z}] are not, since you should do something like this Total@Abs@{X, Y, Z}, but I think even in this case the latter way would be faster, but haven't checked it. – Artes Mar 18 '12 at 13:40