# 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: []
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? Aug 28, 2018 at 17:00

## Perl, 39 33 bytes

/$/,say map$==$_|0,@%for@%=1..<>  Thanks to Ton Hospel for saving 6 bytes Running with the -E perlrun: $ echo 3 | perl -E'@%=1..<>;$a=$_,say map{$a==$_|0}@%for@%'
100
010
001

{$_=1..$^a;.map: {.map: +(*==$^a)}} # 35 bytes  This outputs a list of lists. ### Usage: # give it a lexical name my &identity-matrix = {…} # format it so that it is readable sub readable ( @_ ) { @_.join: "\n" } say readable identity-matrix 10  1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1  # Ruby,38 bytes Returns a 2D array. ->n{(0..n-1).map{|i|s=*n;s[i]=1;s}}  Iterates through each row of the array. For each iteration generates a row of n zeros, then changes one of them to a 1 Usage f=->n{(0..n-1).map{|i|s=*n;s[i]=1;s}} p f [[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]]  A different approach (string): # Ruby, 47 bytes ->n{(0..n-1).map{|i|s='0 '*n;s[i*2]=?1;puts s}}  for each row, makes a string of '0 'repeated n times, changes one of the 0s to 1, and prints it • (0...n) is equivalent to (0..n-1). Jun 22, 2017 at 20:43 # Python 3, 116 107 characters def M(n): x=[] for i in range(n): r=[] for j in range(n): r+=[1 if i==j else 0] x+=[r] return x  ### Output iM(1) [] iM(2) [[1, 0], [0, 1]] iM(3)  • r.append(i) is the same as r+=[i] i think Feb 9, 2016 at 23:27 • There's a lot of further golfing that can be done here – user45941 Mar 22, 2016 at 0:40 • Yeah, 1 if i==j else 0 can be int(i==j). Jun 29, 2017 at 20:03 • 58 bytes Apr 25, 2018 at 19:13 # PARI/GP, 11 5 bytes matid  is sufficient, or n->matid(n)  (11 bytes) as a 'roll-your-own' closure. If you want to work entirely by hand, n->matrix(n,n,i,j,i==j)  (23 bytes) should suffice. # Perl, 31 24 bytes Includes +3 for -p (code contains ' so I can't just use the implied -e) Run with the count on STDIN, e.g. ./diagonal.pl <<< 3  Outputs: 100 010 001  diagonal.pl: #!/usr/bin/perl -p$_=0 x$_;s/./$1$' /g  ## Matlab, 3 bytes eye  Does exactly this. eye(n) for an n-by-n matrix. and also one without eye, 15 bytes: diag(ones(1,n))  # APL (Dyalog Extended), 11 bytes {⍵ ⍵⍴1,⍵/0}  Try it online! Just for fun dfn submission ⍵/0 replicate ⍵ zeros 1, prepend a 1 ⍵ ⍵⍴ mold to ⍵×⍵ square So like for left argument 4 it will construct 1 0 0 0 0  And molding cycles from the beginning so, it will generate 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1  the 4×4 identity matrix. • Are intentionally using the Extended variant? Then you could use ⊤2*⍵ to save a byte over 1,⍵/0 – ovs Sep 11, 2021 at 8:14 • @ovs genius golf! But I am not sure how ⊤2*⍵ works (This works in extended variant too) Sep 13, 2021 at 16:50 • After knowing how this works I will edit the answer along with explanation Sep 13, 2021 at 16:50 • ⊤2*⍵ only works in Extended, in this variant ⊤ without a left argument returns the base-2 digits of the right argument – ovs Sep 13, 2021 at 17:01 # Knight, 35 bytes ;=nP;=i~1W<=i+1i nO S*"0 "n *2i 1 1  Try it online! Outputs a bunch of strings. It works by generating the string 0 0 ... 0  (a space-separated string of $$\n\$$ 0s), then changing the $$\2i\$$th character to 1 and outputting the result for each $$\i\$$ between $$\0\$$ and $$\n-1\$$. Expanded code: ;=n PROMPT ;=i~1 WHILE <(=i +1 i) n OUTPUT (SET (*"0 " n) (*2 i) 1 1)  # Husk, 4 bytes ´Ṫ=ḣ  Try it online! ´ # argdup: use input as both arguments to function Ṫ # table: generate the outer product of all pairs = # equals: 1 if arguments equal, zero otherwise ḣ # heads: 1..input  # Arturo, 36 bytes $=>[unique permutate++@.of:&-1,0]


Try it

# 𝔼𝕊𝕄𝕚𝕟, 3 chars / 6 bytes

Мƕï


Try it here (Firefox only).

I'm finding a lot of these 3-char solutions. It's just a builtin.

# Bonus solution, 11 chars / 22 bytes

⩥ïⓜãĉ⇝+($≔a  Try it here (Firefox only). The code in the interpreter link uses some more bytes to pretty-print output. ### Explanation ⩥ïⓜãĉ⇝+($≔a // implicit: ï=input
⩥ïⓜ         // create a range [0,ï) and map over it
ãĉ⇝      // get a copy of range ã and map over it
+($≔a // output 1 or 0 depending on whether item in first map == item in current map // implicit output  • How does this work? Jan 29, 2016 at 3:24 • It's just a builtin. I'll post a bonus solution soon. Jan 29, 2016 at 3:28 • Alright, updated. Jan 29, 2016 at 3:47 # Mouse, 75 bytes N:1I:(I.N.1+<^1J:(J.I.<^0!32!'1J.+J:)1!32!'(J.N.<^0!32!'1J.+J:)10!'1I.+I:)$


This is a full program that reads from STDIN and prints to STDOUT. Each line will have a single trailing space and there will be one trailing newline at the end of the output.

Explanation:

~ Read N from STDIN
? N:

~ Initialize a row index
1 I:

~ Loop while we've printed fewer than N+1 rows
( I. N. 1 + < ^

~ Initialize a column index
1 J:

~ Print I-1 space-separated zeros
( J. I. < ^
0 !
32 !'
1 J. + J:
)

~ Print 1 and a space
1 !
32 !'

~ Print the remaining zeros
( J. N. < ^
0 !
32 !'
1 J. + J:
)

~ Newline
10 !'

~ Increment the row index
1 I. + I:
)
\$


# Java, 200 Bytes

This is the shortest working java code i could come up with. Nothing to special ;)

class a{public static void main(String[]a){int c=Integer.parseInt(a);int[][]b=new int[c][c];for(int d=0;d<c;d++){for(int e=0;e<c;e++){b[d][d]=1;System.out.print(b[d][e]);}System.out.println();}}}


Partly posting this hoping someone could explain why TNT 's answer is valid (it has no class declaration and no main(String[] args))? I'm new to code golf and i thought that answers had to be a working program?

• The answer in question is a function, which is a valid submission by our rules. You can make this shorter by changing class to interface, which allows you to drop the public.
– user45941
Mar 22, 2016 at 0:39

# Scala, 53 51 bytes

(n:Int)=>Seq.tabulate(n,n){(i,j)=>if(i==j)1 else 0}

• I am unfamiliar with Scala, though is the space in 1 else necessary? Aug 28, 2018 at 17:48
• @JonathanFrech yes, it actually won’t compile without it, with “Invalid literal number” message. Thanks anyway! And you should learn Scala, it is beautiful. Aug 28, 2018 at 17:53

# Ruby 42 bytes

->n{(+*(n-1)).permutation.to_a.uniq}


creates every permutation of the array [1,0,0,0...] and then takes the unique ones. this will end up with the ones we want, in the correct order.

# C++, 111 bytes

I love abusing for loops.

#include <stdio.h>
void f(int n){for(int j,i=0;i++<n;putchar(10))for(j=0;j++<n;putchar(32))putchar(i-j?48:49);}


# Oracle SQL 11.2, 102 bytes

SELECT SUBSTR(RPAD(0,:1,0),:1-LEVEL+2)||1||SUBSTR(RPAD(0,:1,0),LEVEL+1)FROM DUAL CONNECT BY LEVEL<=:1;


# Python 3, 22 bytes

from numpy import*;eye


It's a bit boring, but it's short! Because of discussion on meta, I think this follows the spirit of the rules a bit more closely.

• I'm unsure about your points, why don't you try adding an answer to the meta question, so it can get feedback from more people? The main thing that bothers me about it is the arguments against the empty file being valid, because then you could write a library that defined all functions to make all your answers extremely small. But I'm uncertain of how to differentiate between import and def now that you've brought it up. Feb 3, 2016 at 18:55
• @FryAmTheEggman +1 I'll open it to the floor. Feb 3, 2016 at 19:01

## Jellyfish, 12 bytes

PN(Rri
-


Try it online! This entry is non-competing.

## Explanation

• i is input, and r computes the range from 0 to input-1.
• The operator ( is a left hook. On inputs - and R, it applies R (rotate) to the range and its negated version. This gives the i×i matrix whose rows are the ranges ri, rotated k steps to the right for each row k.
• N computes the logical negation of each entry: 0 goes to 1 and everything else to 0. Since the 0s are on the diagonal, this gives the identity matrix.
• P prints the matrix.

# 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.