vector operations in J
Author Message
vector operations in J

in the phrase book as

cross2=: ((_1: |.[)*(1:|.]))-((1: |.[)*(_1: |. ]))

This seems to be defined for a left-handed system,
rather than the usual right-handed system:

(1 0 0) cross2 (0 1 0)
0 0 _1

The equivalent form for a right-handed system is

cross2=: ((1: |.[)*(_1: |. ]))-((_1: |.[)*(1:|.]))
(1 0 0) cross2 (0 1 0)
0 0 1

I have some computations where I need to do a large
number of such operations, so time and space are of
importance. The vectors are of shape (n,3)\$, so e.g.
seven vectors might be

\$v1
7 3
v1
_0.172588 _0.362598  0.915825
0.636889 _0.277067 _0.719448
_0.737586  0.662711  0.129539
_0.987313  _0.12105  _0.10276
0.309235 _0.554503  0.772593
0.143797 0.0317368  0.989098
0.798938  0.278942 _0.532812

and another seven

v2
_0.844068   _0.52808 _0.0931706
0.778154  _0.363568  _0.512146
0.0137387 _0.0199004   0.999708
_0.92034  _0.157223   0.358127
0.174609   0.113858   0.978033
_0.548721  _0.795738   0.256332
_0.719419   0.419388  _0.553669

The cross-product defined above will not operate on these
arrays without introducing the rank:

v1 cross2"(1) v2
0.517412 _0.789099  _0.214918
_0.11967 _0.233662 _0.0159519
0.665095   0.73915 0.00557351
_0.0595074  0.448157  0.0438215
_0.630288  _0.16754    0.13203
0.795198 _0.579599 _0.0970101
0.0690136  0.825663   0.535742

But for large n, this is not a good solution. For example,
for n=20,000, the time and space (J 3.05  on a Sun SPARC 20,
with 160 MB memory) are

\$v3
20000 3
ts'r=. v3 cross2"(1) v4'
10.9187 1.85261e7

Introducing "1 into the defining expression gives much
better results:

cross3=. ((1: |."1 [)*_1: |."1 ]) - ((_1: |."1 [)*1: |."1 ])
ts'r=. v3 cross3 v4'
0.728745 5.76864e6

Still better, however, is the form:

pm1=. 1&|."1  NB. 1st cyclic permutation
pm2=. 2&|."1  NB. 2nd cyclic permutation
pm12=. 4 : '(pm1 x.)*pm2 y.'
cross=. pm12 - pm12~
ts'r=. v3 cross v4'
0.659872 2.6281e6

What is surprising to me is that if I replace the implicit
definition for pm12 with the tacit form, the result,

pm12=. ([: pm1 [) * [: pm2 ]
cross4=. pm12 - pm12~
ts'r=. v3 cross4 v4'
0.760311 5.77062e6

is slightly slower and uses over twice the memory. All other
tacit forms I have tried give similar results. I guess you
just have to experiment. Does anyone have a faster/smaller
expression for the cross product?

J. Patrick Harrington

P.S.

Another (non-competative) expression tried was

rotate=.1 2"_ |."0 1]

ts'r=. v3 cross5 v4'
5.46043 9.27901e6

Fri, 27 Apr 2001 03:00:00 GMT

 Page 1 of 1 [ 1 post ]

Relevant Pages