24
\$\begingroup\$

Diagonalize a vector into a matrix.

Input

A vector, list, array, etc. of integers \$\mathbf{v}\$ of length \$n\$.

Output

A \$n \times n\$ matrix, 2D array, etc. \$A\$ such that for each element \$a_i \in \mathbf{v}\$,

$$ A = \left( \begin{array}{ccc} a_1 & 0 & \cdots & 0 \\ 0 & a_2 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & a_n \end{array} \right) $$

where the diagonal of \$A\$ is each element in \$\mathbf{v}\$.

Notes

  • This is , so shortest program or function in bytes wins!
  • Construct the Identity Matrix may be of use to you.
  • If the length of \$\mathbf{v}\$ is 0, you may return an empty vector, or an empty matrix.
  • If the length of \$\mathbf{v}\$ is 1, you must return a \$1 \times 1\$ matrix.

Not Bonus

You can receive this Not Bonus if your program is generic across any type, using the type's zero-value (if it exists) in place of \$0\$.

Test Cases

[] -> []
[0] -> [[0]]
[1] -> [[1]]
[1, 2, 3] -> [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
[1, 0, 2, 3] -> [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]
[1, -9, 1, 3, 4, -4, -5, 6, 9, -10] -> [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, -9, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 4, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -4, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, -5, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 6, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, -10]]
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Suggested test case: a vector containing 0 \$\endgroup\$ Commented Jul 14, 2023 at 16:43

40 Answers 40

1
2
1
\$\begingroup\$

Racket, 97 bytes; Not Bonus

(define(f v)(let([n(length v)])(for/list([i(range n)])(list-set(make-list n 0)i(list-ref v i)))))

Try it online!


Explanation

After reading in the input as a list called v, we obtain the length of v and store it as n.

(define (f v)
  (let ([n (length v)])
    ...))

We then loop through the range \$ 0 \le i < n \$ and for each iteration, we return a new list (a row of the matrix) of n length filled with zeros except at the index of i which is filled with the corresponding value from v at index i.

(define (f v)
  (let ([n (length v)])
    (for/list ([i (range n)])
      (list-set (make-list n 0)
                i
                (list-ref v i)))))

The for/list function returns the collected rows after each iteration.

Not Bonus

While the rows start with zeros, any data in v will still be preserved. What this means is that we can pass list of strings to f and receive a matrix with both strings and zeros as the zero-value:

; Strings
(f '("h" "e" "y"))
;;> '(("h" 0 0) (0 "e" 0) (0 0 "y"))

; Symboles
(f '(a b c))
;;> '((a 0 0) (0 b 0) (0 0 c))

; Characters
(f '(#\d #\e #\f))
;;> '((#\d 0 0) (0 #\e 0) (0 0 #\f))

Have a wonderful weekend!

\$\endgroup\$
1
\$\begingroup\$

KamilaLisp v0.3, 21 bytes

[* #0[(⌼ =)#0#0]∘⍳∘⍴]

The code generates a range vector from 0 to the size of the argument; then it computes the Cartesian product of the range vector and itself using equality as the functor, therefore computing the identity matrix. Each row of the identity matrix is then multiplied by the initial vector.

\$\endgroup\$
1
\$\begingroup\$

Japt, 7 bytes

£çT hYX

Try it

£çT hYX     :Implicit input of array U
£           :Map each X at index Y
 ç          :  Fill U with
  T         :    0
    hYX     :  Replace the element at index Y with X
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 5 bytes

āDδQ*

Try it online or verify all test cases.

Explanation:

āDδQ   # Create an identify matrix the size of the input-length:
ā      #  Push a list in the range [1, (implicit) input-length]
 D     #  Duplicate it
  δ    #  Apply double-vectorized:
   Q   #   Check whether the values are equal
    *  # Multiply the values in each row with the values of the (implicit) input-list
       # (after which the matrix is output implicitly as result)
\$\endgroup\$
1
\$\begingroup\$

Kotlin, 65 bytes

{a:IntArray->Array(a.size){i->IntArray(a.size).also{it[i]=a[i]}}}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Hi there, hello! Welcome to the Code golf stack exchange! Very neat first answer you've got here - I hope you enjoy your stay on the site. \$\endgroup\$
    – lyxal
    Commented Jul 17, 2023 at 22:32
0
\$\begingroup\$

Pyth, 8 bytes

.eXmZQkb

Try it online!

Explanation

.eXmZQkbQ    # implicitly add Q
             # implicitly assign Q = eval(input())
.e      Q    # enumerated map Q over lambda, b, k
   mZQ       # list of zeros the same length as Q
  X   kb     # replace position k with b
\$\endgroup\$
0
\$\begingroup\$

PowerShell Core, 77 bytes

if($l=($a=$args).count){($k=1..$l)|%{$r++
$c=1
,($k|%{$a[$_-1]*!($c++-$r)})}}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

BQN, 6 bytes

⊢×⍋=⌜⍋

Try it at BQN online!

Explanation

⊢×⍋=⌜⍋
      ⍋  Grade up; for our purposes, gives a list of unique integers of the same
          length as the argument
  ⍋      Grade up again
    =⌜   Create an equality table
         This gives an identity matrix the same size as the length of the argument
⊢×       Multiply each row by the corresponding element of the argument
\$\endgroup\$
0
\$\begingroup\$

Scala 3, 70 bytes

x=>x.zipWithIndex.map((e:Int,i:Int)=>Seq.fill(x.size)(0).updated(i,e))

Attempt This Online!

\$\endgroup\$
-2
\$\begingroup\$

Python 3.8 (pre-release), 67 bytes

lambda a:[[x*(i==j) for i,x in enumerate(a)]for j in range(len(a))]

A 42-byte solution that only works if all elements are unique:

lambda a:[[x*(x==y) for x in a]for y in a]

Try it online!

\$\endgroup\$
5
  • 4
    \$\begingroup\$ The input isn't guaranteed to be unique though, so this answer is invalid. \$\endgroup\$
    – The Thonnu
    Commented Jul 14, 2023 at 20:34
  • \$\begingroup\$ Hence, the disclaimer. \$\endgroup\$
    – Hunaphu
    Commented Jul 14, 2023 at 23:04
  • 3
    \$\begingroup\$ Even with the disclaimer, the answer is invalid, and so you need to delete it. \$\endgroup\$
    – The Thonnu
    Commented Jul 15, 2023 at 7:52
  • 2
    \$\begingroup\$ I would recommend keeping this answer, and adding a version (even if it's much longer) that does work in the same post. That's the typical way of handling interesting but technically invalid answers. \$\endgroup\$
    – rydwolf
    Commented Jul 16, 2023 at 3:07
  • \$\begingroup\$ Thanks for the suggestion Rydwolf. I considered the longer solution to similar to already posted answers. \$\endgroup\$
    – Hunaphu
    Commented Jul 16, 2023 at 16:59
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.