In APL, how to turn a vector (of length n) into a diagonal matrix (nxn)?

I had a J program that I wrote in 1985 (on vax vms). One section created a diagonal matrix from a vector.

a=(n,n)R1,nR0
b=In
a=bXa

Maybe it was not J, but APL in ascii, but these lines work in current J (with corresponding changes in primitive functions). But not in the APL (gnu, NARS2000, or ELI). I get a domain error in the last line. Is there an easy way to do this without a loop?

+4
source share
5 answers

Your code is a transliteration of the ASCII APL. Corresponding J code:

a=.(n,n)$1,n$0
b=.i.n
a=.b*a

! APL ( Dyalog APL) , . , b a :

a←(n,n)⍴1,n⍴0
b←⍳n
ab×[1]a

! ( ):

a←(n,n)⍴1,n⍴0
b←⍳n
a←b(×⍤0 1)a

!

+6

- ⍉ :

      n←5 ◊ z←(n,n)⍴0 ◊ (1 1⍉z)←⍳n ◊ z
1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5
+3

X, APL ( @Adám ):

(2⍴S)⍴((2×S)⍴1,-S←⍴X)\X

, .

, , ( ):

((⍴Q)⍴X)×Q←P∘.=P←⍳⍴X
((⍴Q)⍴X)×Q←P Pρ1,(P←≢X)ρ0
+1

:

(n∘.=n)×(2ρρn)ρn←⍳5

should provide you with the following in most APL

1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5
0
source

This solution works in the old ISO Apl:

a←(n,n)⍴v,(n,n)⍴0
0
source

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


All Articles