[Question]
  [
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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program or function in bytes wins!
* [Construct the Identity Matrix](https://codegolf.stackexchange.com/questions/70365/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]]
```
  
[Answer]
# [K (ngn/k)](https://codeberg.org/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!](https://ngn.bitbucket.io/k#eJxLs6qu0LJVrqjl4krT0ORKUzAAYkMQVjBSMAbTBnCWriWQMFYwUdAFIlMFMwVLBV1DAwDqfA0a)
[Answer]
# [Haskell](https://www.haskell.org/), 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.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 2 bytes
```
Xd
```
The code uses the builtin function `Xd` (which corresponds to MATLAB's `diag`). [Try it online!](https://tio.run/##y00syfn/PyLl//9oQx0FAx0FIx0F41gA "MATL ‚Äì Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
J=√æ`a
```
[Try it online!](https://tio.run/##y0rNyan8/9/L9vC@hMT/h9vdNbMeNe7j4vr/PzpWRyHaEEzoKBjpKBhDmbqWOgpAylhHwQTIAWFTHQUzHQWgsK6hQSwA "Jelly ‚Äì 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](https://github.com/DennisMitchell/jelly), 3 bytes
```
jn`
```
[Try it online!](https://tio.run/##y0rNyan8/z8rL@H/4XZ3zaxHjfu4uP7/j47VUYg2BBM6CkY6CsZQpq6ljgKQMtZRMAFyQNhUR8FMRwEorGtoEAsA "Jelly ‚Äì 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 `j¬¨` owing to all inputs being nonzero (which is not guaranteed by the spec).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 4 bytes
```
diag
```
[Try it online!](https://tio.run/##y08uSSxL/f//f0pmYrqGoZWhgeZ/AA "Octave ‚Äì Try It Online")
# [Python](https://www.python.org), 23 bytes
```
from numpy import*
diag
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhbb04rycxXySnMLKhUycwvyi0q0uFIyE9MhsjsKijLzSjRAAhpFiXnpqRqGOoZGmpqaEGmYIQA)
[Answer]
# [Haskell](https://www.haskell.org/), 34 bytes
```
foldr(\a m->(a:(0<$m)):map(0:)m)[]
```
[Try it online!](https://tio.run/##fVLLbsMgELz7K@aQA0hraZ20lWrF/YN@AeGAXLu1YmIr9rHfXgo4fdiRQMCyM8MurPbDTOem711bnVw79G9XcTKw@YswpeDjzkpZWjMKLqWVSru5mebaTM2ECiqDH0JpgtKSbh4H1@9/SBGR4j9C2BMOC05gP8OZI/xz5KBY3eH7ayv52ttvuU20/JngzYHw4J2wHglPBA/nBW@S3M9b6BAlKeCYJclzfEWS5/jKJM/LL5ICXn6ZFHCsQpLnWKUkz0sVtdRZZk138f3i@@gV47W7zNhBiRZdVQ0EbyU@IToaJI45fltMu6@67c375PJ6HL8B "Haskell ‚Äì Try It Online")
Uses the recursive method [from Magma](https://codegolf.stackexchange.com/a/262878/20260) of expanding the matrix with a new value in the top left, but with `foldr` and `<$`.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 6 bytes
```
x:·µí-¬¨*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpKuoVLsgqWlJWm6FisrrB5unaR7aI3WkuKk5GKo6IKbrtGxXNEGQGwIwjoKRjoKxhCWATJH11JHAUgZ6yiYADkgbKqjYKajABTWNTSIhZgGAA)
Multiplies the identity matrix like other answers.
```
x:·µí-¬¨*
x       [0 .. length - 1]
 :      Duplicate
  ·µí     Outer product with
   -        Subtract
    ¬¨   Logical NOT
     *  Multiply
```
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
*[:=#\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/taKtbJVj/mtypSZn5CukKairQ1gwOk1Bx8oQXcgICI2B0OQ/AA "J ‚Äì Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ƒóD»∑=√ó
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCU5N0QlQzglQjclM0QlQzMlOTcmZm9vdGVyPSZpbnB1dD0yJTJDMyUyQzUmZmxhZ3M9)
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
```
[Answer]
# [Haskell](https://www.haskell.org), 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!](https://ato.pxeger.com/run?1=fVJLTsMwFJRY5hRTiUUiOdFLCwgEZsOWHcsoiwicT8mnatxUqnITNt0gzgSnwbHbQlLJln9vZvxsP83HV56076Is9_vPjUz92--nFB2vArcKvCDHNhdrgQoZr5IVsoiCoBR1JnN0fhjf59ihwLIvOF_ybjYr-vCR-M6k-rnopGjla9KKFhyRA9XcKGaIYo8dIhpCNf8hoUbC_wjDnGFhcAZSfdiTho9bGhSjM3R-bCQfR_MpN8nm3zGoZcFwpYJhXDPcMCjYD2lyyXk_pB6yWAWkb7HypF9h5Um_0sqT-YVVQOaXVgHpKlh50lWy8mSqGHux41RJUSu_rDbyRa6fa1yizZutWpKyRPGGKFWeI3COBj3cgjUeHnycvBYb-x0d_Qs)
[Answer]
# [Go](https://go.dev), ~~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!](https://ato.pxeger.com/run?1=ZU9LasMwEN3rFNOsJBgXp2lLa9DCN-jemCBSKciJx0a1vRHe9BrdmEIv0xvkNpVikwS6EO-jmeG9r-99M53uWrU7qL2GWllizNZt47r7lam7FRuUAyN_-s4kL6dP09OOD0VpqRM8L8qZedM4sLjNpFMUzgzeZbJWB83P_3jUxAchWByrbsd0JlNmDVgpK6_lUNhyZK6oSqlHlkvVtpreeY5OBFt3vaNxSfIbk5zzcgGeWfqATMISyLMZRlxIemHrK0N4QNjc6vS_lbwiBNggPAYR3xPCM0Kwk3U8O55bbdFSDDAXi2k8e3PhxpG4JXHhJqqrFGF9aTRNM_4B)
# [Go](https://go.dev), ~~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!](https://ato.pxeger.com/run?1=ZVBBasMwEKRXvWLxSQKlJE2TtgEd8oMWcjMmqIkUlNiKkR1DEbr3D72EQj_Rn7Sv6SpOYkNBo51d7Q6z-vjc7I_fpVzt5EZBIY0lxBTl3tW3iS7q5OtQ68Hjz7s-2BXodAHSvmW0SbMFo_M0i9HrvQPDlzPhpEWRxruZKOROUXzlubK0YYzEpm2_qZEOFCyI0WCE2HolmtRkgbh0mwkVyFzIslR2TefcMSyr-uBsaP383rycDEW_lIEnxlYwExANGVt70obAz2R4ZaOOcbjjMO7nw_-lwRMHDGMO95hETDhMOWB5MIqy4bTZkhsbDbTLRTeePDvUyC01ll25jlmXMhwnZ-dVjcWNT2TCk1fECoFnjVAInYTrWNUXrFCP5P3t23sSeEumF_IQOom8L5GjxPlnj8c2_gE)
[Answer]
# [Python](https://www.python.org), ~~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!](https://ato.pxeger.com/run?1=fVJLTsMwEJVY5hRDVwlMpEnLt5UXnMPywqG2sLCSKA4LbsAd2HQDd4LT4E9a0VZy5Ngz7z2P7dH7_B7ep5e-2-2-3iZdP_zcb5UGXUo0jKp1AbofoQXTgVxbJrkRjJO4sqorZbWxIW835po1afvvxcek3PQsnXLAgBecCwQuBPqIBIYpJU3A_TxnCEuEVcIQyI8QU4T3IQXFQU_nW46kx9nylPtXqX5E8MsK4cYn4b9FuEPwcN3QyQHnYy4bqmQFFE_J8hRvkeUp3jLLU3pFVkDplVkBxS5keYpdyvKUuui_oghmMtgHOx1s4j3m_WYqvxgNBi4Z9AEDGEbTTeVCS2PVdoEQNQDtqORroaxTQTaLnqyNJR0M0jkvr5Ih977-Aw)
[Outputs by modifying arguments](https://codegolf.meta.stackexchange.com/a/4942/70761).
[Answer]
# Dyalog APL, 9 bytes
Thanks to [@att](https://codegolf.stackexchange.com/users/81203/att) for -4
```
‚ä¢√ó‚ç§1‚çã‚àò.=‚çã¬≠‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å§‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å°‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å¢‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å£‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å¢‚Å§‚Å™‚Äè‚Å†‚Äé‚Å™‚Å°‚Å™‚Å†‚Å™‚Å£‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚Å†‚Å°‚Äå¬≠
‚ä¢          # ‚Äé‚Å°v
 √ó‚ç§1       # ‚Äé‚Å¢multiplied row-wise with
    ‚çã‚àò.=‚çã  # ‚Äé‚Å£the identity matrix of size (#v)
```
üíé Created with the help of [Luminespire](https://vyxal.github.io/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](https://vyxal.github.io/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`.
[Answer]
# PARI/GP, 11 bytes
```
matdiagonal
```
Builtins are always a sad answer, aren't they?
[Answer]
# [Factor](https://factorcode.org/) + `math.matrices`, 15 bytes
```
diagonal-matrix
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoQckijKTU4sVCopSS0oqC4oy80oUilMLS1PzQKKZ@QrWXFzVXApAUK1QC6UN4CxDJJaBgpGCMZBfqxD9PyUzMT0/LzFHF2x@xf/izNyCnFTdksSknFQ9hbwchViF1MTkjP8A "Factor ‚Äì Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 9 bytes [SBCS](https://github.com/abrudz/SBCS)
```
-‚àò‚ç≥‚ç§‚â¢‚Üë‚ç§0‚ä¢
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=033UMeNR7@ZHvUsedS561DYRyDB41LUIAA&f=S1N41LuGK03BAIgNQVjBSMEYTBvAWYfWWwJJYwUTIAuETRXMFCyBtCFIk3pJanGJOlideqI61DQNAwUNQwWNR11NOkaamppAvRo6j3pXPOqYARR61LvY5FHXIlNNBQ11M3UFc00A&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
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.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 34 bytes
```
x=>x.map((v,i)=>x.map(_=>i--?0:v))
```
[Try it online!](https://tio.run/##NU1LCoMwEL3KLBOYEa220JboQUIowU9JUSNVQm6fjlIX77t472ODXduvWzaafdenQaWo6phNdhEioJNneKnaETX5I0iZnlobBF0chHBBKP@W7ggsJULFYccV4YbANRW5MccWP7R@Xv3YZ6N/i0FEyaPpBw "JavaScript (Node.js) ‚Äì Try It Online")
[Answer]
# Mathematica, 14 bytes
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yUzMT0/LzHHN7GkKLPif1p0UGJeemq0oY6hgY5hbKy@fkBRZl7JfwA)
```
DiagonalMatrix
```
[Answer]
# 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.
[Answer]
# [TypeScript](https://www.typescriptlang.org/)'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!](https://www.typescriptlang.org/play?#code/C4TwDgpgBAYgPANQHwF4DeBtAklAlgOygGsIQB7AMygQF0AuTAKT0JPKtruYgA9gJ8AEwDOULAH4EGRvQAMAX3kAoJaEhQAKhGHAAjFBSw4GWTSQBuJQHorUOwD1xq8NC06ATAaMZdAGiju-gDMZta2Dk5qrtrAQV7wPv6y-oFQIUhhdlCOzupuwAAs8cZ+UAC0AJz+pUH+Bf5l9eUArP4AbP5V5bqmGTZZOUA)
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.
[Answer]
# [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 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](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I-RMurXNt66j&in=WzEsIDAsIDIsIDNd)
# 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](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I0y6tc23riuj&in=WzEsIDAsIDIsIDNd)
~~`#√§L¬∫¬µ√ç¬∑¬Æ+¬£`~~ (broken in current version)
`#L¬∫¬µ√ç¬∑¬Æ+¬£`
Adds zero to the result to force the entries above the diagonal to be printed.
---
# Itr, [8 bytes](https://bsoelch.github.io/OneChar.js/?lang=itr&src=I0y6tc23rqM&in=WzEsIDAsIDIsIDNd)
`#L¬∫¬µ√ç¬∑¬Æ¬£`
the `√§` before the `L` is no longer necessary in newer versions
[Answer]
# [R](https://www.r-project.org), 20 bytes
```
\(x)diag(x,sum(x|1))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZbYjQqNFMyE9M1KnSKS3M1KmoMNTUhUjcT0jSSNTQ1uUCUAZQ2hNJGML6OkY4xnG2AwlPQtdRRAFLGOgomQA4Im-oomOkoAIV1DQ1g9ixYAKEB)
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](https://www.r-project.org), 54 bytes
```
\(x,`[`=matrix)c(x,rep(0*x,n<-sum(x|1)))[n+1,n,T][n,n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3zWI0KnQSohNscxNLijIrNJOB3KLUAg0DrQqdPBvd4tJcjYoaQ01Nzeg8bUOdPJ2Q2Og8nbxYqO6ENI1kDU1NLhBlAKUNobQRjK9jpGMMZxug8BR0LXUUgJSxjoIJkAPCpjoKZjoKQGFdQ6CJEHsWLIDQAA)
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](https://www.r-project.org), 27 bytes
```
\(v,x=seq(a=v))v*!x%o%x-x^2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuha7YzTKdCpsi1MLNRJtyzQ1y7QUK1TzVSt0K-KMICpuJqRpJGtoanKBKAMobQiljWB8HSMdYzjbAIWnoGupowCkjHUUTIAcEDbVUTDTUQAK6xoCTYTYs2ABhAYA)
Heavily inspired by [@Kirill L.'s answer to the linked challenge](https://codegolf.stackexchange.com/a/163556/55372).
[Answer]
# [Python](https://www.python.org), 23 bytes
```
import numpy
numpy.diag
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhbbM3ML8otKFPJKcwsqucCkXkpmYjpEdldBUWZeiQZCWCPaSMdYxzRWUxOiAGYMAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 25 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.125 bytes
```
L√û‚ñ°*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+UD0iLCIiLCJMw57ilqEqIiwiIiwiW10gLT4gW11cblswXSAtPiBbWzBdXVxuWzFdIC0+IFtbMV1dXG5bMSwgMiwgM10gLT4gW1sxLCAwLCAwXSwgWzAsIDIsIDBdLCBbMCwgMCwgM11dXG5bMSwgMCwgMiwgM10gLT4gW1sxLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDBdLCBbMCwgMCwgMiwgMF0sIFswLCAwLCAwLCAzXV1cblsxLCAtOSwgMSwgMywgNCwgLTQsIC01LCA2LCA5LCAtMTBdIC0+IFtbMSwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMF0sIFswLCAtOSwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAxLCAwLCAwLCAwLCAwLCAwLCAwLCAwXSwgWzAsIDAsIDAsIDMsIDAsIDAsIDAsIDAsIDAsIDBdLCBbMCwgMCwgMCwgMCwgNCwgMCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAtNCwgMCwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAwLCAtNSwgMCwgMCwgMF0sIFswLCAwLCAwLCAwLCAwLCAwLCAwLCA2LCAwLCAwXSwgWzAsIDAsIDAsIDAsIDAsIDAsIDAsIDAsIDksIDBdLCBbMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgLTEwXV0iXQ==)
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](https://vyxal.github.io/Luminespire).
[Answer]
# [Rust](https://www.rust-lang.org/), ~~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!](https://tio.run/##fY3NCoMwEITvfYrxIgoxxNqWtiFPIjn0x5RATCHVXNRnT6O9tVKY3WW@2WVd/@qCsmgv2mY5BtN0UBBh9Oe01kc5LsQIT00TF/js2r6DE765JfXSGDdylno6aGgLRqkZXK1llPCxTW4KfHO/PpJMZelyJPP8i7BfVK4ggi1BtRqwP1lxIoijIthFM9ee4EAQcVF@Xk/hDQ "Rust ‚Äì Try It Online")
# [Rust](https://www.rust-lang.org/), ~~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!](https://tio.run/##dY5NDoIwEIX3nmLcmDYWAqImFuhGj0DcEBYIrSEpYCo0MYSzYyvu0GR@8r6ZvBnVP7tpEg2IKKEXLvJedttz@3gxpOkmTTLssCsvIpsJY4PkHchYu5I3CIdW1X0HKta8WKefklBazj52IbMhWgUVVA14risHlVaZiVibMqrRHq/zytjBsCpv9zUSlEYImwesXYZx@MUz8BbEXxICOwLBL@79HzknAqYFBPZG2DwQOBIw2PHns@P0Bg "Rust ‚Äì Try It Online")
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 53 bytes
```
![l](https://$ "Push the length of the stack to the stack")![:](https://$ "Duplicate the top item on the stack")![:](https://$ "Duplicate the top item on the stack")![0](https://$ "Push the number (0-9)")![)](https://$ "Greater than, less than. Push 1 or 0 to the stack.")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![\](https://$ "Reflect the cursor direction")![;](https://$ "Halt")
![$](https://$ "Move the top element of the stack back 1")![:](https://$ "Duplicate the top item on the stack")![@](https://$ "Move the top elemnt of the stack back 2")![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![\](https://$ "Reflect the cursor direction")
![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![2](https://$ "Push the number (0-9)")![1](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.")![\](https://$ "Reflect the cursor direction")![:](https://$ "Duplicate the top item on the stack")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![{](https://$ "Shifts the entire stack left or right")![:](https://$ "Duplicate the top item on the stack")![}](https://$ "Shifts the entire stack left or right")![0](https://$ "Push the number (0-9)")![l](https://$ "Push the length of the stack to the stack")![5](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![&](https://$ "If the register is empty, pop the top element of the stack and move it to the register. Else push the value of the register to the stack.")![=](https://$ "Pop 2 values of the stack, push 1 if they are equal and 0 otherwise")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![$](https://$ "Move the top element of the stack back 1")![n](https://$ "output a number in decimal")![~](https://$ "Delete the top element of the stack")![9](https://$ "Push the number (0-9)")![o](https://$ "output a character")
![~](https://$ "Delete the top element of the stack")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![0](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.")![\](https://$ "Reflect the cursor direction")![~](https://$ "Delete the top element of the stack")![{](https://$ "Shifts the entire stack left or right")![~](https://$ "Delete the top element of the stack")![a](https://$ "Push the hexadecimal (10-15)")![o](https://$ "output a character")
```
Hover over any symbol to see what it does
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoibDo6MCk/XFw7XG4kOkA6P3ZcXFxuMS0yMS5cXDomezp9MGw1LSY9PyRufjlvXG5+MS0xMC5cXH57fmFvIiwiaW5wdXQiOiIiLCJzdGFjayI6IjI5MiAxOSAyNyAxMiA4MTIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoiY2hhcnMifQ==)
[Answer]
# [Pip](https://github.com/dloscutoff/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!](https://ato.pxeger.com/run?1=m724ILNgWbSSboBS7IKlpSVpuhbL0rVcI5XTIRyo2JpoQx0FAx0FIx0FY5g6AA)
### 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
```
[Answer]
# [Uiua](https://uiua.org), ~~7~~ 6 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
√ó‚äû=.‚çè.
```
-1 thanks to Bubbler
[Try it!](https://uiua.org/pad?src=RiDihpAgw5fiip49LuKNjy4KCkYgW10KRiBbMV0KRiBbMSAyIDEgMl0KRiBbMSAwIDEgMl0=)
```
√ó‚äû=.‚çè.
     .  # duplicate
 ‚äû=.‚çè   # identity matrix
√ó       # multiply
```
[Answer]
# [Python](https://www.python.org), 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!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3nVJS0xTSNBI1rfJsixLz0lM1clLzgFxN66LUktKivOhojUxb2yxNrcTozNi0_CKFTIXMPIU8MDMLwoSapBxdUJSZV6KRqakAV5emATHTUEfB0FBTE6oUZjkA)
# [Python](https://www.python.org), 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](https://codegolf.stackexchange.com/a/70368/106829) answer.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3nVJS0xTSNBI1rSpsc1LzgAzrotSS0qK86GiDWK1M7ejE6MzYWG0QR6NCuy5TMy2_SCFTITNPoSgxLz1Vo0IzFmqScnRBUWZeiUampgJcTZoGRJWhjoKhoSZMKcxyAA)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes + Not Bonus
```
‚≠Ü¬πÔº•Œ∏Ôº•Œ∏√ó‚ÅºŒºŒæŒΩ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBjqKICoQjgVkpmbWqzhWliamFOskaujUKGpo5CnCQLW//9HRwPVG@goGOkoGMfG/tctywEA "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Explanation:
```
   Œ∏        Input array
  Ôº•         Map over elements
     Œ∏      Input array
    Ôº•       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.
]