g | x | w | all
Bytes Lang Time Link
070Scala 3240227T092743Zt9dupuy
006BQN240226T235342ZDLosc
067Python 3.8 prerelease230714T202400ZHunaphu
006Uiua231012T195722Zchunes
009Itr230731T150701Zbsoelch
077PowerShell Core230731T214721ZJulian
008Pyth230717T180714ZCursorCo
065Kotlin230717T174216ZCactusro
006Pip P230717T160138ZDLosc
00505AB1E230717T120037ZKevin Cr
007Japt230717T112217ZShaggy
009Dyalog APL230714T165247ZRubenVer
062TypeScript's Type System230717T004021Znoodle m
053><> Fish230716T174155Zmousetai
002MATL230714T170146ZLuis Men
021KamilaLisp v0.3230716T103159ZKamila S
006Nekomata230716T052611Zalephalp
055Python230715T051305ZSuperSto
034Haskell230716T030214Zxnor
nanGo230714T174031Zbigyihsu
081Rust230715T215125Zleo848
039Haskell230715T151445ZMagma
067Haskell230715T125134Zmatteo_c
007K ngn/k230715T085445Zsouth
3125Vyxal230715T054444Zlyxal
033Excel230715T045132ZJos Wool
014Mathematica230715T045717Z138 Aspe
097Racket230715T003454ZEd The &
034JavaScript Node.js230715T000831Zl4m2
009APLDyalog Unicode230714T200809Zatt
005Thunno 2230714T171825ZThe Thon
023Python230714T183607ZThe Thon
004Octave230714T183225ZHunaphu
015Factor + math.matrices230714T181438Zchunes
020R230714T174853Zpajonk
011Charcoal230714T173356ZNeil
011PARI/GP230714T171816ZRubenVer
006J230714T171748ZJonah
066Python230714T171616ZSapherey
005Jelly230714T164611ZUnrelate

Scala 3, 70 bytes

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

Attempt This Online!

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

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!

Uiua, 7 6 bytes

×⊞=.⍏.

-1 thanks to Bubbler

Try it!

×⊞=.⍏.
     .  # duplicate
 ⊞=.⍏   # identity matrix
×       # multiply

Itr, 9 bytes

#äLºµÍ·®£

prints the elements of the matrix separated by spaces, with , separating the rows. Does not print the zero entries above the diagonal.

online interpreter

Explanation

#          ; read array from standard input
 äLº       ; push the range from zero to array.length-1
    µÍ     ; replace each element in the range with a vector having a one at the given index
           ; this will give an identity matrix of size array.length represented as 2D array 
      ·    ; point-wise multiplication
       ®   ; convert result to matrix
        £  ; print

Itr, 10 9 bytes

#äLºµÍ·®+£ (broken in current version)

#LºµÍ·®+£

Adds zero to the result to force the entries above the diagonal to be printed.


Itr, 8 bytes

#LºµÍ·®£

the ä before the L is no longer necessary in newer versions

PowerShell Core, 77 bytes

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

Try it online!

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

Kotlin, 65 bytes

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

Try it online!

Pip -P, 6 bytes

g*EY#g

(The flag is only necessary to format the output in a readable way; any of -P, -p, -S will do.)

Attempt This Online!

Explanation

g*EY#g
     g  ; List of command-line arguments
    #   ; Length
  EY    ; Identity matrix of that size
g*      ; Multiply each row by the corresponding element of g

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)

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

Dyalog APL, 9 bytes

Thanks to @att for -4

⊢×⍤1⍋∘.=⍋­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌­
⊢          # ‎⁡v
 ×⍤1       # ‎⁢multiplied row-wise with
    ⍋∘.=⍋  # ‎⁣the identity matrix of size (#v)

💎 Created with the help of Luminespire

Dyalog APL, 16 bytes + Not Bonus

The only other applicable scalar type are characters, where APL uses the space as the empty character, so this code also does

,⍨∘≢⍴∊⍤(⊢↑¨⍨1+≢)­⁡‎‎⁡⁠⁢⁡‏‏⁡⁠⁡‌⁢‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‏⁡⁠⁡‌⁣‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏⁡⁠⁡‌⁤‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁣‏‏⁡⁠⁡‌⁢⁡‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁤‏‏⁡⁠⁡‌⁢⁢‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏⁡⁠⁡‌­
    ⍴             # ‎⁡Reshape
,⍨∘≢              # ‎⁢to (#v)*(#v) matrix 
     ∊⍤           # ‎⁣the flattened list of lists built by
        ⊢ ¨       # ‎⁤taking each item of v
         ↑ ⍨      # ‎⁢⁡and padding it with
            1+≢   # ‎⁢⁢(#v) zeros
💎

Created with the help of Luminespire

This works by noticing that, if the diagonalized matrix is read as a single list, row by row, each entry of v is spaced with as many zeros as the length of v.

TypeScript's Type System, 62 bytes

type F<V>={[I in keyof V]:{[J in keyof V]:J extends I?V[J]:0}}

Try it at the TypeScript Playground!

It's been a little while since I've golfed in TS types, so it's possible (though I think unlikely) that I missed a shorter way to do this. This one is pretty simple, but I'll leave an explanation anyway:

type F<V> =           // type F taking generic tuple type V
  { [I in keyof V]:   // for each I in V's indices:
    { [J in keyof V]: //   for each J in V's indices:
      J extends I     //     are J and I the same type?
        ? V[J]        //       if so, index into V with J
        : 0           //       otherwise, 0
    }                 //   end
  }                   // end

I tried putting keyof V into type F<V,K=keyof V> but that doesn't work since the compiler complains that K could be a type unrelated to an array key, and it doesn't save enough bytes for //ts-ignore to be worth it.

><> (Fish), 53 bytes

l::0)?\;
$:@:?v\
1-21.\:&{:}0l5-&=?$n~9o
~1-10.\~{~ao

Hover over any symbol to see what it does

Try it

MATL, 2 bytes

Xd

The code uses the builtin function Xd (which corresponds to MATLAB's diag). Try it online!

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.

Nekomata, 6 bytes

x:ᵒ-¬*

Attempt This Online!

Multiplies the identity matrix like other answers.

x:ᵒ-¬*
x       [0 .. length - 1]
 :      Duplicate
  ᵒ     Outer product with
   -        Subtract
    ¬   Logical NOT
     *  Multiply

Python, 56 55 bytes

-1 byte thanks to xnor

def f(a,i=0):
 for b in a:l=a[i]=[0]*len(a);l[i]=b;i+=1

Attempt This Online!

Outputs by modifying arguments.

Haskell, 34 bytes

foldr(\a m->(a:(0<$m)):map(0:)m)[]

Try it online!

Uses the recursive method from Magma of expanding the matrix with a new value in the top left, but with foldr and <$.

Go, 135 130 bytes

func(v[]int)(A[][]int){for i,_:=range v{r:=make([]int,len(v))
for j,_:=range v{e:=0
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}

Attempt This Online!

Go, 141 136 bytes + Not Bonus

func f[T any](v[]T)(A[][]T){for i,_:=range v{r:=make([]T,len(v))
for j,_:=range v{var e T
if i==j{e=v[i]}
r[j]=e}
A=append(A,r)}
return}

Attempt This Online!

Rust, 83 81 bytes

Simple and dirty imperative solution.

-2 bytes by taking a slice instead of a vec

|v:&[i8]|{let l=v.len();let mut r=vec![vec![0;l];l];for i in 0..l{r[i][i]=v[i]}r}

Try it online!

Rust, 126 124 bytes + Not Bonus

The Copy bound is technically too strict and a Clone bound would be enough, but it would also be one byte longer :shrug:.

fn f<T:Default+Copy>(v:&[T])->Vec<Vec<T>>{let l=v.len();let mut r=vec![vec![T::default();l];l];for i in 0..l{r[i][i]=v[i]}r}

Try it online!

Haskell, 39 bytes

f[]=[];f(a:b)=(a:map(0*)b):map(0:)(f b)

Recursively generates the matrix by appending a value at the top left corner of a smaller matrix.

Haskell, 67 bytes

f v=m.(m.).h where m g=map g[0..length v-1];h z i j|i==j=v!!i|1>0=z

Attempt This Online!

K (ngn/k), 7 bytes

{x*=#x}

My first K post. I tried real hard to make a Bubbler train work here but failed.

Try it online!

Vyxal, 25 bitsv2, 3.125 bytes

LÞ□*

Try it Online!

The P flag on the permalink is to make the test cases pass (for some strange reason, I never made it not check exact string representation.) Individual cases all produce the right output with vyxal list syntax without the flag.

Explained

LÞ□*­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌­
L     # ‎⁡Push the length of the input
 Þ□   # ‎⁢Construct an NxN identity matrix
   *  # ‎⁣and pair-wise vectorise multiplication
💎

Created with the help of Luminespire.

Excel, 33 bytes

=IFERROR(MUNIT(ROWS(A1#))*A1#,"")

Excel, 39 bytes + Not Bonus

=IFERROR(IF(MUNIT(ROWS(A1#)),A1#,0),"")

Input is vertical spilled range A1#.

Having to deal with the empty vector is inconvenient; otherwise these would be just 21 and 27 bytes respectively.

Mathematica, 14 bytes

Try it online!

DiagonalMatrix

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!

JavaScript (Node.js), 34 bytes

x=>x.map((v,i)=>x.map(_=>i--?0:v))

Try it online!

APL(Dyalog Unicode), 9 bytes SBCS

-∘⍳⍤≢↑⍤0⊢

Try it on APLgolf!

Left-pads each \$v_i\$ to a vector of length \$i\$ and implicitly mixes.

Each row's fill elements match the type of the corresponding element of the vector.

Thunno 2, 5 bytes

ėDȷ=×

Try it online!

Inspired by Unrelated String's Jelly answer.

Explanation

ėDȷ=×  # Implicit input
ė      # Length range
 D     # Duplicate
  ȷ    # Outer product over:
   =   #  Check for equality
    ×  # Multiply by the input
       # Implicit output

Python, 23 bytes

import numpy
numpy.diag

Attempt This Online!

Octave, 4 bytes

diag

Try it online!

Python, 23 bytes

from numpy import*
diag

Attempt This Online!

Factor + math.matrices, 15 bytes

diagonal-matrix

Try it online!

R, 20 bytes

\(x)diag(x,sum(x|1))

Attempt This Online!

The diag built-in almost works here, but fails for inputs of length 1, where it produces identity matrix of size of the input. Unless specified nrow argument.


Less boring - without diag built-in:

R, 54 bytes

\(x,`[`=matrix)c(x,rep(0*x,n<-sum(x|1)))[n+1,n,T][n,n]

Attempt This Online!

Idea: construct a vector such that every entry of the input \$x\$ of length \$n\$ is followed by \$n\$ zeros. A matrix with \$x\$ in the first row and followed by \$n\$ rows of zeros works too. Then, we can put this in a \$n\times n\$ matrix resulting in \$x\$ on the diagonal.

Ungolfed:

\(x){n=length(x)
m=matrix(c(x,rep(0,n^2)), nrow=n+1, ncol=n, byrow=TRUE)
matrix(m, nrow=n, ncol=n)}

R, 27 bytes

\(v,x=seq(a=v))v*!x%o%x-x^2

Attempt This Online!

Heavily inspired by @Kirill L.'s answer to the linked challenge.

Charcoal, 11 bytes + Not Bonus

⭆¹EθEθ×⁼μξν

Try it online! Link is to verbose version of code. Explanation:

   θ        Input array
  E         Map over elements
     θ      Input array
    E       Map over elements
        μ   Row index
       ⁼    Equals
         ξ  Column index
      ×     Multiplied by
          ν Inner element
⭆¹          Pretty-print

Using And instead of Times would have made the code minusculely more efficient but this way the code produces empty strings on the non-diagonal entries when given a string array as input.

PARI/GP, 11 bytes

matdiagonal

Builtins are always a sad answer, aren't they?

J, 6 bytes

*[:=#\

Try it online!

Python, 66 bytes

def f(a):n=range(len(a));return[[(i==j)*a[i]for i in n]for j in n]

Attempt This Online!

Python, 66 bytes

def f(a):x=len(a);return[[0]*i+[a[i]]+[0]*(x+~i)for i in range(x)]

This solution was inspired by this answer.

Attempt This Online!

Jelly, 5 bytes

J=þ`a

Try it online!

J=þ`     Identity matrix:
  þ      table
J        [1 .. length]
   `     with itself
 =       by equality.
    a    Vectorizing logical AND; replace ones with elements of the vector.

If output can be flat:

Jelly, 3 bytes

jn`

Try it online!

j      Join the vector on
 n     the list of, for each element, if it doesn't equal
  `    itself.

If the empty vector didn't have to be handled, this could tie non-flat as jn`sL; it passes all current test cases as owing to all inputs being nonzero (which is not guaranteed by the spec).