# 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? – Jonathan Frech Aug 28 '18 at 17:00

# Jolf, 7 + 1 = 8 bytes

Replace all ☺s with \x01 and \xad with a soft hyphen, or use the online interpreter. (Turn pretty output on for one byte.)

!☺!X\xad☺j
!X       eye
j  (the input)
!☺         get the data
implicit printing


Probably more interesting, a solution without a builtin is 11 + 1 = 12 bytes

ZXZyjjdP=Sn
Zyjj       create a matrix of width = height = j (input)
ZX    d      matrix map
=Sn  if x-marker is y-marker
P     as a number


# R, 50 bytes

f=function(n)matrix(c(1,rep(c(rep(0,n),1),n-1)),n)


Without using diag(), because I started coding without checking if there was a command for that... Also, I like my solution, despite being way too long.

• 36 bytes by abusing recycling (but gives a warning about non-multiple of length in recycling) – Giuseppe Jan 15 '18 at 19:32

# Octave, 15 bytes

Because built-ins are no fun!

@(x)(k=1:x)==k'
@(x)~~diag(1:x)


Try it online!

The first one creates a vector from 1, 2, .. x, and compares it to itself transposed, expanding it to a square matrix where the diagonal elements are 1.

The second one creates a diagonal matrix with 1, 2, .. x is on the diagonal, then negates it twice, to get the diagonal equal 1, 1, .. 1.

# JavaScript, 75 74 bytes

n=>eval("for(a=[],i=0;i<n;i++){a[i]=[];for(j=0;j<n;)a[i][j]=+(i==j++)};a")


Can be improved, probably.

## If n=0 isn't necessary... 70 bytes

n=>eval("for(a=[i=0];i<n;i++)for(a[i]=[j=0];j<n;)a[i][j]=+(i==j++);a")

• Since the zero by zero identity matrix is of questionable existence, a=[],i=0 could be golfed to a=[i=0]. – Jonathan Frech Aug 28 '18 at 16:59
• I feel like one could argue that your other version also does not appropriately address n=0, since it outputs [], not [[]]; open for interpretation, though ... – Jonathan Frech Aug 28 '18 at 17:08
• Based on this consensus, I think you could even drop the +(...). – Jonathan Frech Aug 28 '18 at 17:12
• @JonathanFrech True. this challenge predates that consensus tho – Conor O'Brien Aug 28 '18 at 17:40

## PowerShell, 52 bytes

param($a)1..$a|%{$d++;(1..$a|%{+($d-eq$_)})-join' '}


Since the only built-in .NET class for matrices is ... umm ... inadequate, shall we say, we're just going to construct and output a string representation here...

Takes input $a then executes a double-for-loop over range 1..$a. Each outer loop we increment helper variable $d (the first loop, since $d isn't initialized, turns $d++ into $null + 1 = 1 ... in PowerShell logic it makes sense), and each inner loop is simply an integer-cast with + of an equality between $d and the current element $_. Each inner loop is -joined together with spaces so it prints nicely, and each outer loop causes a newline, so output code is pretty cheap.

### Example

PS C:\Tools\Scripts\golfing> .\construct-identity-matrix.ps1 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


import Data.Matrix
identity


Maybe a little bit boring.

Usage example:

Prelude Data.Matrix> identity 4
( 1 0 0 0 )
( 0 1 0 0 )
( 0 0 1 0 )
( 0 0 0 1 )


# Ruby, 56 48 bytes

->n{(([1]+[0]*n)*(n-1)+[1]).each_slice(n).to_a}


Explanation:

Concatenates n - 1 sequences of 1 followed by n 0s into an array, and appends 1 to the end. Then slices the result into n arrays of length n and evaluates to an array having the slices as its elements.

Per Alex A., shaved 8 bytes by putting it in the form of a lambda.

# Ruby,38 bytes

Returns a 2D array.

->n{(0..n-1).map{|i|s=[0]*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=[0]*n;s[i]=1;s}}
p f[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]]


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). – Value Ink Jun 22 '17 at 20:43

# 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


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


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


# R, 32 31 bytes

function(n)+outer(1:n,1:n,"==")


Try it online!

Thanks to Kirill L. for -1 byte

Alternative to Ivanneke's solution, but obviously far longer than just plain old diag.

• You can swap *1 for +: 31 bytes – Kirill L. Apr 26 '18 at 18:48
• @KirillL. ah, yes, thank you. – Giuseppe Apr 26 '18 at 20:40

# R, 28 bytes

function(n,x=1:n)+!x%o%x-x^2


Try it online!

For pure fun, just another attempt at a non-built-in R solution. Uses the shortcut %o% version of the outer function.

# 05AB1E, 4 bytes

°¨œÙ


Try it online!

Unique permutations of (10^input)[0:-1]

• Nice answer! An alternative is LDδQ, for 4 bytes as well. – Mr. Xcoder Aug 28 '18 at 15:16
• @Mr.Xcoder First time I see δ being used. Nice approach as well! – Kevin Cruijssen Aug 28 '18 at 15:25

# Perl 6,  41 37  35 bytes

{$/=1..$_;$/.map: {$/.map: {+($^a==$_)}}} # 41 bytes
{$/=1..$_;$/.map: {$/.map: +(*==$_)}} # 37 bytes {$_=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" }


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


# 𝔼𝕊𝕄𝕚𝕟, 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? – lirtosiast Jan 29 '16 at 3:24 • It's just a builtin. I'll post a bonus solution soon. – Mama Fun Roll Jan 29 '16 at 3:28 • Alright, updated. – Mama Fun Roll Jan 29 '16 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[0]);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. – Mego Mar 22 '16 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? – Jonathan Frech Aug 28 '18 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. – Jacob Aug 28 '18 at 17:53 # Ruby 42 bytes ->n{([1]+[0]*(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. – FryAmTheEggman Feb 3 '16 at 18:55 • @FryAmTheEggman +1 I'll open it to the floor. – Ogaday Feb 3 '16 at 19:01 # 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) [[1]] iM(2) [[1, 0], [0, 1]] iM(3)  • r.append(i) is the same as r+=[i] i think – Seadrus Feb 9 '16 at 23:27 • There's a lot of further golfing that can be done here – Mego Mar 22 '16 at 0:40 • Yeah, 1 if i==j else 0 can be int(i==j). – Zacharý Jun 29 '17 at 20:03 • 58 bytes – hakr14 Apr 25 '18 at 19:13 ## 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. # 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";
}
?>


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