Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
2  
I believe you will find this Q/A informative. –  Mr.Wizard Mar 17 '12 at 13:04
add comment

2 Answers

up vote 9 down vote accepted

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 ]
share|improve this answer
    
I can't test in Mma at the moment, but I belive this is correct. –  Szabolcs Mar 17 '12 at 12:55
    
Looks right to me. –  Mr.Wizard Mar 17 '12 at 13:01
add comment

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].

share|improve this answer
    
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.) –  kguler Mar 18 '12 at 1: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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.