# Construct the Identity Matrix

The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.


This is , so the shortest code in bytes wins.

• Given an integer input n ... -- I assume you mean a natural number? Commented Aug 28, 2018 at 17:00

# picTuring - 16 States (320 bytes)

I thought this challenge might be a good chance to show off my new Turing Machine interpreter.

0 * 0 * r
0 _ 1 * r
1 * 2 1 l
2 * 2 * l
2 _ d * l
d _ f * r
d 0 d 1 l
d 1 p 0 r
p * p * r
p _ q * r
q * q * r
q _ 2 0 l
f * f _ r
f _ g * r
g 1 g _ r
g 0 r 1 r
r * r * l
r _ c * r
c _ n * d
c 0 o * d
c 1 i * d
o * e 0 u
i * j 0 r
j * h 1 u
h * k * r
k _ halt * *
k * c * *
e * c * r
n * r * l


The input must be in binary (1 / 0), with the number terminating at the head (the white circle).

How to Run it:

In case you didn't realize that the link in the header leads to my interpreter, you can find it here -> http://fred-choi.com/projects/picTuring/index.html

Here is the compressed test case (since my interpreter does not support permalinks yet):

AwAlH0QRhBaGLTgJjCSMg AwAgVCoQTgUKB9EBGcI6ogJhSANrDtmgTkgCYmyyVIBmaclolqBrIADpOtdxP17ckAR0awxESbzFIcoArAYQGSOKpABzcbG2pta3T2i44sEzComkAYx12kAOzTlYd0AHsXb3AEtvsF4QAKY8AK7U-hAAVsawsRAAFrgRyRAA1uKZSIkAhngALmhgsJkQdhAlsKHlOs6WEHhAA


To use it, just hover over save, paste the compressed code in the text box, and click load.

To edit the tape, make sure you're in "Type" mode (Edit -> Paint), then double click the tape, and a red box should show up, indicating that you're now editing the tape.

Once you're finished, hit Edit -> Ok to save the tape, then Controls -> Run. Controls -> Reset will restore the tape to when you hit Edit -> Ok.

Again, this is interpreter is still indev, I don't have a manual yet, so feel free to leave comments if I left anything out.

# PHP, 106 bytes

<?php $i=$argv[1];for($j=0;$j<$i;$j++){for($h=0;$h<$i;$h++){$l="0 ";if($h==$j)$l="1 ";echo$l;}echo"\n";}?>  Based on a double for loop, it uses the command-line argument for the input. php 70365.php 3 1 0 0 0 1 0 0 0 1  Expanded code: <?php$i = $argv[1]; for($j = 0; $j <$i; $j++) { for($h = 0; $h <$i; $h++) {$l="0 ";
if($h ==$j)
$l="1 "; echo$l;
}
echo "\n";
}
?>


## Sage, 15 bytes

identity_matrix


Exactly what it says on the tin

Try it online

Thanks to Lynn for pointing out that I was being a doofus.

• Why not eta-reduce this to identity_matrix?
– lynn
Commented Aug 21, 2016 at 18:21

# Samau, 5 bytes

,;=o


It's a function that takes a number and return a 2D array.

,;=o
,      range from 0 to n-1
;     duplicate
o  take the outer product by
=   equality


# Jelly, 2 bytes

=þ


Try it online!

# PHP, 64 bytes

for(;$i<$argn**2;$m?:$k++)echo$k==$m?:0,($m=++$i%$argn)?" ":" ";  Try it online! # Rust, 59 bytes |n|{let mut l=vec![vec![0;n];n];for i in 0..n{l[i][i]=1};l}  Defines an anonymous function, creates a vector of vectors of the specified length, sets the diagonals to 1 and returns it. Boring, but shorter than any iterator-based approaches due to .collect overhead. Alternatively, if returning an iterator of iterators is allowed it can be done in 44 characters: |n|(0..n).map(|i|(0..n).map(|j|(j==i)as u8))  # tinylisp repl, 107 bytes (d =(q((A R C S)(i C(=(c(e R C)A)R(s C 1)S)A (d #(q((A R S)(i R(#(c(=()R S S)A)(s R 1)S)A (d f(q((S)(#()S S  Using the repl saves 6 bytes in implied closing parentheses at the ends of lines. Defines a function f which takes a positive integer and returns the identity matrix of that size as a nested list. Try it online! ### Explanation The function = constructs a row in the matrix. Its arguments are (in order) an Accumulator, the Row number, the current Column number, and the Size of the matrix. If the column is not zero (i C ...), then cons a number to the accumulator (1 if the row and column are equal, 0 otherwise) (c (e R C) A), decrease the column number (s C 1), and recurse (= ...). Otherwise, return the accumulator A. The function # constructs the matrix as a list of rows. Its arguments are an Accumulator, the current Row number, and the Size of the matrix. If the row number is not zero (i R ...), then generate a row (=()R S S) and cons it to the accumulator (c ... A), decrease the row number (s R 1), and recurse (# ...). Otherwise, return the accumulator A. Finally, the function f is simply a single-argument wrapper function that calls #. ## Clojure, 45 bytes #(for[i(range %)](assoc(vec(repeat % 0))i 1))  # PHP, 49 bytes function($n){for(;$n--;)$k[$n][$n]=1;return $k;};  There is a bit of a caveat with this answer, and I will delete it or mark it as non-competing if it is deemed invalid. The array returned by this function technically only has n elements, those being a 1 at every intersection. ie: 0:0 1:1, 2:2, etc However, not only does this satisfy the definition of the identity matrix as given by the question: The identity matrix is one that has 1s spanning from the top left down to the bottom right It also works if used as an identity matrix, as an empty value in an array in PHP is treated as 0 if used arithmetically. # Axiom, 68 bytes f(n:PI):Matrix INT==matrix([[(i=j=>1;0)for i in 1..n]for j in 1..n])  test and results (30) -> for i in 1..3 repeat output f(i) [1] +1 0+ | | +0 1+ +1 0 0+ | | |0 1 0| | | +0 0 1+ Type: Void  # Mathematica ,26 bytes without using IdentityMatrix Boole[#==#2]&~Array~{#,#}&  # Python 2, 52 bytes y=x=2**input() while~-x:x/=2;print str(bin(y+x))[3:]  Try it online! Using binary representation of powers of 2. ## PowerShell, 45 bytes {param($n)0..--$n|%{"$(,0*$_+1+,0*($n-$_))"}}  Try It Online! # Vim, 47 keystrokes "zy$␘a@q␛"xYoa␛"zPy$qqo␛@"0␛q@x3Gqqr1jlq@x1G2dd  ␘ is CtrlX and ␛ is Esc ## Explanation "zy$␘           Save n for use later
a@q␛"xY         Create the macro x that repeats the macro q n-1 times
oa␛"zPy$Create an anonymous macro that inserts a character n times qqo␛@"0␛q@x Create the macro q that adds a new line with n zeroes and run it n times 3G Go to the top-left corner of the matrix qqr1jlq@x Redefine q as a macro that replaces the character at the cursor with a one and moves the cursor one step down-right. Run q n times 1G2dd Delete the two lines used in macro defenitions  # Excel VBA, 55 52 43 Bytes Anonymous VBE immediate window function that takes input as number from cell [A1] and outputs the identity matrix to the range of [A1].Resize(n,n) [A1].Resize([A1],[A1])="=1*(Row()=Column())  -2 bytes thanks to Engineer Toast ### Previous Version n=[A1]:[A1].Resize(n,n)=0:For i=1To n:Cells(i,i)=1:Next  • Save 1 byte: "=1*(Row()=Column())" Commented Apr 25, 2018 at 15:18 # Husk, 4 bytes ´Ṫ=ḣ  Try it online! ### Explanation ´Ṫ=ḣ -- example input: 2 ḣ -- range: [1,2] ´ -- duplicate argument: [1,2] [1,2] Ṫ -- outer product by = -- | equality: [[1==1,1==2],[2==1,2==2]] -- : [[1,0],[0,1]]  # Tcl, 92 bytes proc I n {time {incr j;set a "";set i 0;time {lappend a [expr [incr i]==$j]} $n;puts$a} $n}  Try it online! # Gol><>, 10 bytes IR0PlF}D|;  Try it online! The output for n = 5 looks like this: [1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1]  ### How it works IR0PlF}D|; IR0P Take input n, then fill the stack with that many 0s and then make the top 1; stack = [0 ... 0 1] lF..| Do the following n times... }D Rotate the stack once to the right, and print the whole stack ; Terminate  # 05AB1E, 6 bytes Lã€Ësô  Try it online. Explanation: L # List in range [1,n] # i.e. 3 → [1,2,3] ã # Cartesian power of this list # i.e. [1,2,3] → [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] €Ë # Check for every pair if they are equal or not # i.e. [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] # → [1,0,0,0,1,0,0,0,1] sô # Split it into parts equal to the input # i.e. [1,0,0,0,1,0,0,0,1] and 3 → [[1,0,0],[0,1,0],[0,0,1]]  • Alternative 6-byter °¨IF=Á Commented Aug 28, 2018 at 15:01 • @Kaldo Ah, that's quite a bit different than my approach, but also pretty cool. And I just saw your 4-byte answer, +1 from me. :) Commented Aug 28, 2018 at 15:22 # Jellyfish, 8 7 bytes P&O=ri  Try it online! ### Explanation P&O=ri ri Range(input) & With that list and itself, O make a table (outer product) = using vectorized equality P Print as matrix  # Vyxal, 2 bytes Þ□  Try it Online! Vyxal literally has a builtin for this. # Factor + math.matrices, 15 bytes identity-matrix  Try it online! # BQN, 4 bytes =⌜˜↕  Anonymous tacit function; returns a 2D array. Try it at BQN online! ### Explanation  ↕ Range(argument) =⌜ Create an equality table ˜ between that list and itself  # Pip-P, 6 bytes _=BMCa  Try It Online! Just for completeness sake, here's the shortest non-builtin answer that I could find in Pip. In other words, an answer without the usage of EY. _=BMCa Input is "a" MCa Map over all x,y pairs in an a by a coordinate grid _=B Is the x-coordinate equal to the y-coordinate? Implicit output joined by newlines (-P flag)  # Nibbles, 6 5 bytes (10 nibbles) .;,$.@==$_  . # map across each value of ,$            # 1..input
;              # (saving this range)
.           #   map across each value of
@          #   the saved range (1..input again)
==\$_      #     are the two values equal?


# K (ngn/k), 1 byte

=


Try it online!

# Pyt, 5 bytes

řĐɐ=Ɩ


Try it online!

ř              implicit input; create řange [1,2,...,n]
Đ             Đuplicate
ɐ=           for ɐll pairs: are elements equal?
Ɩ          cast to Ɩnteger; implicit print


# Nekomata, 3 bytes

ᵒ-¬


Attempt This Online!

ᵒ-     Generate a 2d table with subtraction
¬    Logical not (converts 0 to 1 and other numbers to 0)


# Fortran (GFortran), 110 bytes

allocatable K(:,:);read*,n;allocate(K(n,n));K=0;forall(i=1:n)K(i,i)=1
do i=1,n;print*,(K(i,j),j=1,n);enddo;end


Try it online!