According to Rosetta Code, there are two idiomatic ways of creating identity matrix in APL:
1. ID←{∘.=/⍳¨ ⍵ ⍵}
2. ID←{⍵ ⍵ ρ 1, ⍵ρ0}
How does the (2) work? Why is this better than the (1), which uses Outer Product that is considered idiomatic approach in APL?
1,⍵⍴0
creates a vector that consists of a 1
followed by ⍵
zeros. So, the length of this vector is ⍵+1
.
⍵ ⍵ ⍴
covers an ⍵
-by-⍵
matrix. Copies of the vector will be fit left to right and top to bottom. The first copy will cover the entire first row and overflow to the second row, e.g. for ⍵=5
:
1 0 0 0 0
0 . . . .
. . . . .
. . . . .
. . . . .
Now, the second copy will come in with a little indent on the second row:
. . . . .
. 1 0 0 0
0 0 . . .
. . . . .
. . . . .
and so forth until we cover all of the matrix. It's not necessarily an exact cover, the last copy may be cut off. If you picture this process further, you can see that the 1
-s will land on the main diagonal.
I don't know why this should be a better approach than the one using outer product. Either seems fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With