Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in APL how do I turn a vector (of length n) into a diagonal matrix (nxn)?

Tags:

j

apl

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

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

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

like image 421
osmanfb1 Avatar asked Dec 28 '17 16:12

osmanfb1


2 Answers

Your code is an ASCII transliteration of APL. The corresponding J code is:

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

Try it online! However, no APL (as of yet — it is being considered for Dyalog APL) has major cell extension which is required on the last line. You therefore need to specify that the scalars of the vector b should be multiplied with the rows of the matrix a using bracket axis notation:

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

Try it online! Alternatively, you can use the rank operator (where available):

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

Try it online!

like image 76
Adám Avatar answered Sep 28 '22 15:09

Adám


A more elegant way to address diagonals is ⍉ with repeated axes:

      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
like image 22
Jürgen Sauermann Avatar answered Sep 28 '22 14:09

Jürgen Sauermann