The most idiomatic way to create an identity matrix in APL

According to the Rosetta Code, there are two idiomatic ways to create an identical matrix in APL:

1. ID←{∘.=/⍳¨ ⍡ ⍡} 2. ID←{⍡ ⍡ ρ 1, ⍡ρ0} 

How does it work (2)? Why is this better than (1) that uses the Outer Product, which is considered an idiomatic approach in the APL?

+3
source share
3 answers

If you compare the performance of two expressions, 2 clearly win:

 cmpx'{∘.=/⍳¨ ⍡ ⍡}1000' '{⍡ ⍡ ⍴ 1, ⍡⍴0}1000' {∘.=/⍳¨ ⍡ ⍡}1000 β†’ 2.4EΒ―3 | 0% βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ•βŽ• * {⍡ ⍡ ⍴ 1, ⍡⍴0}1000 β†’ 5.7EΒ―5 | -98% βŽ• 

If you think that the interpreter should do it when processing two expressions, (2) also works much less: attach the scalar to vec and change the form of the result, whereas in (1) it should create two vectors, build an external product with equal comparison. Plus, this includes β€œeveryone”, which (according to some sources) is not considered a β€œpure APL” ... And, obviously, if you think about the ideas implemented by these two algorithms, (2) is much nicer and more elegant. But this is only my opinion;)

+3
source

1,⍡⍴0 creates a vector consisting of 1 , followed by ⍡ zeros. Thus, the length of this vector is ⍡+1 .

⍡ ⍡ ⍴ covers the matrix ⍡ -by- ⍡ . Copies of the vector will correspond from left to right and from top to bottom. The first copy will cover the entire first line and overflow in the second line, for example. for ⍡=5 :

 1 0 0 0 0 0 . . . . . . . . . . . . . . . . . . . 

Now the second copy will come in slightly indented in the second line:

 . . . . . . 1 0 0 0 0 0 . . . . . . . . . . . . . 

etc. until we cover the whole matrix. This is not necessarily an accurate cover; the latest copy may be turned off. If you look at this process further, you will see that 1 -s will land on the main diagonal.

I do not know why this should be a better approach than one that uses an external product. Everything seems to be fine.

+5
source

{⍡ ⍡⍴ (⍡ + 1) ↑ 1} ... fast

{∘. = ⍨⍳⍡} ... nice

;)

+2
source

Source: https://habr.com/ru/post/1491741/


All Articles