49
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Given an integer input n ... -- I assume you mean a natural number? \$\endgroup\$ Aug 28, 2018 at 17:00

106 Answers 106

26
\$\begingroup\$

MATL, 2 bytes

Xy

A translation of my Octave answer.

Try it online.

A 4 byte version with no built-ins (thanks to Luis Mendo):

:t!=
:     take input n and a generate row array [1,2,...n]
 t    duplicate
  !   zip
   =  thread compare over the result
\$\endgroup\$
5
  • 7
    \$\begingroup\$ It must have been difficult, to translate this very sophisticated code :D \$\endgroup\$
    – flawr
    Jan 28, 2016 at 18:40
  • 12
    \$\begingroup\$ @flawr You have no idea. This is truly my masterpiece. \$\endgroup\$ Jan 28, 2016 at 18:40
  • 2
    \$\begingroup\$ This seems vaguely familiar... ;) \$\endgroup\$ Jan 28, 2016 at 18:42
  • 1
    \$\begingroup\$ Now I see why you were asking! :-D \$\endgroup\$
    – Luis Mendo
    Jan 28, 2016 at 18:54
  • 5
    \$\begingroup\$ Without builtins: :t!= \$\endgroup\$
    – Luis Mendo
    Jan 28, 2016 at 18:56
20
\$\begingroup\$

TI-BASIC, 2 bytes

identity(Ans

Fun fact: The shortest way to get a list {N,N} is dim(identity(N.

Here's the shortest way without the builtin, in 8 bytes:

randM(Ans,Ans)^0

randM( creates a random matrix with entries all integers between -9 and 9 inclusive (that sounds oddly specific because it is). We then take this matrix to the 0th power.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ "that sounds oddly specific because it is" TI-BASIC is weird. O_o \$\endgroup\$
    – Doorknob
    Jan 29, 2016 at 13:48
  • \$\begingroup\$ Hell yes. TI-BASIC. +1 \$\endgroup\$ Jun 30, 2017 at 19:40
  • \$\begingroup\$ isn't the shortest way to get a list {N,N}, umm, {N,N}? \$\endgroup\$
    – Cyoce
    Jul 2, 2017 at 23:05
  • 3
    \$\begingroup\$ @Cyoce No; dim( and identity( are each one byte because TI-BASIC is tokenized. \$\endgroup\$
    – lirtosiast
    Jul 3, 2017 at 21:45
18
\$\begingroup\$

Julia, 9 3 bytes

eye

This is just a built-in function that accepts an integer n and returns an nxn Array{Float64,2} (i.e. a 2D array). Call it like eye(n).

Note that submissions of this form are acceptable per this policy.

\$\endgroup\$
2
  • \$\begingroup\$ I see what you did there! Nice one! \$\endgroup\$ Jan 29, 2016 at 21:41
  • \$\begingroup\$ This also works in Math.JS \$\endgroup\$
    – ATaco
    Jun 29, 2017 at 6:53
18
\$\begingroup\$

APL, 5 bytes

∘.=⍨⍳

This is a monadic function train that accepts an integer on the right and returns the identity matrix.

Try it here

\$\endgroup\$
0
16
\$\begingroup\$

Python 2, 42 bytes

lambda n:zip(*[iter(([1]+[0]*n)*n)]*n)[:n]

An anonymous function, produces output like [(1, 0, 0), (0, 1, 0), (0, 0, 1)],

First, creates the list ([1]+[0]*n)*n, which for n=3 looks like

[1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]

Using the zip/iter trick zip(*[iter(_)]*n to make groups of n gives

[(1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]

Note that the 1 comes one index later each time, giving the identity matrix. But, there's an extra all-zero row, which is removed with [:n].

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Damn that zip/iter trick is ingenious \$\endgroup\$
    – seequ
    Feb 9, 2016 at 20:58
14
\$\begingroup\$

Octave, 10 4 bytes

@eye

Returns an anonymous function that takes a number n and returns the identity matrix.

\$\endgroup\$
5
  • \$\begingroup\$ @eye is sufficient. \$\endgroup\$
    – flawr
    Jan 28, 2016 at 18:37
  • \$\begingroup\$ @flawr Thanks, I knew there was a way to do it like that but I always forget :P \$\endgroup\$ Jan 28, 2016 at 18:39
  • \$\begingroup\$ eye produces the identity matrix in a lot/some numerically oriented languages. \$\endgroup\$
    – flawr
    Jan 28, 2016 at 18:50
  • \$\begingroup\$ What does the @ do? \$\endgroup\$
    – Cyoce
    Jul 2, 2017 at 23:06
  • \$\begingroup\$ @Cyoce @ is the "function handle operator", it works like a lambda and also as a reference to a particular function, so for instance, @(x)x.^2 is the squaring function and @sqrt is a reference to the square root function. You can read more about that here \$\endgroup\$
    – Giuseppe
    Jan 3, 2018 at 18:29
12
\$\begingroup\$

R, 4 bytes

diag

When given a matrix, diag returns the diagonal of the matrix. However, when given an integer n, diag(n) returns the identity matrix.

Try it online

\$\endgroup\$
10
\$\begingroup\$

Jelly, 4 bytes

R=€R

Doesn't use a built-in. Try it online!

How it works

R=€R    Main link. Input: n

R       Range; yield [1, ..., n].
   R    Range; yield [1, ..., n].
 =€     Compare each.
        This compares each element of the left list with the right list, so it
        yields [1 = [1, ..., n], ..., n = [1, ..., n]], where comparison is
        performed on the integers.
\$\endgroup\$
5
  • 26
    \$\begingroup\$ This code is unacceptably long. \$\endgroup\$
    – flawr
    Jan 28, 2016 at 18:53
  • 5
    \$\begingroup\$ @flawr Twice the length of the shortest one. That's indeed an unusual encounter. \$\endgroup\$
    – Rainer P.
    Jan 28, 2016 at 18:55
  • 1
    \$\begingroup\$ @flawr Yes, and no shorter than J. FAIL! \$\endgroup\$
    – Adám
    Feb 10, 2016 at 15:27
  • 5
    \$\begingroup\$ In modern versions of Jelly, is two bytes, and makes fun of the longer answers. \$\endgroup\$
    – Lynn
    Aug 19, 2016 at 9:57
  • \$\begingroup\$ @Lynn That's still twice as long as the shortest oneS. \$\endgroup\$
    – Adám
    Aug 21, 2016 at 18:29
10
\$\begingroup\$

J, 4 bytes

=@i.

This is a function that takes an integer and returns the matrix.

\$\endgroup\$
2
  • \$\begingroup\$ I think you can do it in 3: =i. \$\endgroup\$ Sep 21, 2016 at 18:39
  • \$\begingroup\$ @SamElliott that doesn't work. For example, (=i.) 10 => 0 0 0 0 0 0 0 0 0 0 \$\endgroup\$
    – Cyoce
    Jul 3, 2017 at 0:03
8
\$\begingroup\$

JavaScript ES6, 68 62 52 bytes

Saved 10 bytes thanks to a neat trick from @Neil

x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z)))

Trying a different approach than @Cᴏɴᴏʀ O'Bʀɪᴇɴ's. Could possibly be improved.

\$\endgroup\$
5
  • \$\begingroup\$ This was exactly what I wrote before I scrolled down to find out that you'd beaten me to it. \$\endgroup\$
    – Neil
    Jan 28, 2016 at 19:57
  • \$\begingroup\$ So, in response to your challenge, I give you the (in hindsight) obvious x=>[...Array(x)].map((_,y,x)=>x.map((_,z)=>+(y==z))) for a saving of 10 bytes. \$\endgroup\$
    – Neil
    Jan 28, 2016 at 19:59
  • \$\begingroup\$ @Neil Thanks a lot! I'll mention that it's your trick in the answer. \$\endgroup\$ Jan 28, 2016 at 20:12
  • 1
    \$\begingroup\$ x=>[...Array(x)].map((_,y,x)=>x.map(_=>+!y--)) \$\endgroup\$
    – l4m2
    Apr 25, 2018 at 17:47
  • \$\begingroup\$ @l4m2 May be it will be better to post your own answer because the user is inactive \$\endgroup\$
    – EzioMercer
    Feb 13, 2023 at 12:48
8
\$\begingroup\$

Pyth, 7 bytes

XRm0Q1Q

Try it online: Demonstration

Creating a matrix of zeros and replacing the diagonal elements with ones.

\$\endgroup\$
2
  • \$\begingroup\$ You can save one byte by removing the final Q \$\endgroup\$
    – Jim
    Jun 22, 2017 at 18:43
  • 1
    \$\begingroup\$ @jim Thanks, but that would actually be not allowed. The feature (implicit Q at the end) was implemented after the challenge was posted. \$\endgroup\$
    – Jakube
    Jun 22, 2017 at 22:40
8
\$\begingroup\$

Haskell, 43 37 bytes

f n=[[0^abs(x-y)|y<-[1..n]]|x<-[1..n]]

Pretty straightforward, though I think one can do better (without a language that already has this function built in, as many have done).

Edit: dropped some bytes thanks to Ørjan Johansen

\$\endgroup\$
5
  • 7
    \$\begingroup\$ You can cheat the fromEnum as sum[1|x==y]. \$\endgroup\$
    – xnor
    Jan 29, 2016 at 0:31
  • \$\begingroup\$ pretty sure you can remove the space in fromEnum (y==x) \$\endgroup\$
    – Cyoce
    Jul 2, 2017 at 23:07
  • \$\begingroup\$ @xnor One byte shorter than that: 0^abs(x-y). \$\endgroup\$ Jan 3, 2018 at 16:56
  • 2
    \$\begingroup\$ @xnor Oh, you just used 0^(x-y)^2 yourself in another answer, even shorter. \$\endgroup\$ Jan 3, 2018 at 18:12
  • \$\begingroup\$ @ØrjanJohansen Yes, seeing your comment was nice timing :) \$\endgroup\$
    – xnor
    Jan 3, 2018 at 18:16
7
\$\begingroup\$

Retina, 25

Credit to @randomra and @Martin for extra golfing.

\B.
 0
+`(.*) 0$
$0¶0 $1

Try it online.

Note this takes input as a unary. If this is not acceptable, then decimal input may be given as follows:

Retina, 34

.+
$0$*1
\B.
 0
+`(.*) 0$
$0¶0 $1

Try it online.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ ...whoa. Retina is becoming powerful as a language for more than regex. \$\endgroup\$ Jan 28, 2016 at 21:02
  • \$\begingroup\$ @ETHproductions yes, though this is answer pretty much all regex substitution. The only special thing is the use of $*0 to replace a number n with n 0s. \$\endgroup\$ Jan 28, 2016 at 21:06
7
\$\begingroup\$

Python 3, 48

Saved 1 byte thanks to sp3000.

I love challenges I can solve in one line. Pretty simple, build a line out of 1 and 0 equal to the length of the int passed in. Outputs as a 2d array. If you wrap the part after the : in '\n'.join(), it'll pretty print it.

lambda x:[[0]*i+[1]+[0]*(x+~i)for i in range(x)]
\$\endgroup\$
1
  • 3
    \$\begingroup\$ x-i-1 -> x+~i \$\endgroup\$
    – Sp3000
    Jan 28, 2016 at 21:58
6
\$\begingroup\$

Haskell, 54 bytes

(#)=replicate
f n=map(\x->x#0++[1]++(n-x-1)#0)[0..n-1]

f returns the identity matrix for input n. Far from optimal.

\$\endgroup\$
1
  • \$\begingroup\$ You can save a handful of bytes using a list comprehension instead of a map call. \$\endgroup\$ Jan 29, 2016 at 9:23
6
\$\begingroup\$

C, 59 or 59 56 or 56

Two versions of identical length.

3 bytes saved due to suggestion from anatolyg: (n+1) --> ~n

Iterates i from n*n-1 to zero. Prints a 1 if i%(n+1) is zero, otherwise 0. Then prints a newline if i%n=0 otherwise a space.

i;f(n){for(i=n*n;i--;)printf(i%n?"%d ":"%d\n",!(i%~n));}

i;f(n){for(i=n*n;i--;)printf("%d%c",!(i%~n),i%n?32:10);}
\$\endgroup\$
6
  • 1
    \$\begingroup\$ n+1 is too dull. Use ~n instead! \$\endgroup\$
    – anatolyg
    Jan 29, 2016 at 0:23
  • \$\begingroup\$ Thanks! I should have spotted that, because it occured to me when I looked at NBZ's challenge today. \$\endgroup\$ Jan 29, 2016 at 0:31
  • \$\begingroup\$ I'm not too familiar with C. What does i; do? \$\endgroup\$
    – Cyoce
    Aug 20, 2016 at 22:56
  • \$\begingroup\$ @Cyoce i; just declares the variable i. In C you always have to declare a variable before using it, indicating the type so the compiler knows how much memory to allocate. With the GCC compiler, if you don't specify a type it is assumed to be int. \$\endgroup\$ Aug 21, 2016 at 0:55
  • 1
    \$\begingroup\$ You can take 1 more byte off of the second one, since tabs are allowed, you can replace 32, with 9. \$\endgroup\$
    – Bijan
    Mar 29, 2017 at 22:40
6
\$\begingroup\$

Lua, 77 75 65 bytes

x,v=z.rep,io.read()for a=1,v do print(x(0,a-1)..'1'..x(0,v-a))end

Well, I'm not sure if lua is the best language for this with the two period concatenation... But hey, there's a shot at it. I'll see if there's any improvements to be made.

EDIT:

I figured something out on accident which I find rather odd, but, it works.

In Lua, everyone knows you have the ability to assign functions to variables. This is one of the more useful CodeGolf features.

This means instead of:

string.sub("50", 1, 1) -- = 5
string.sub("50", 2, 2) -- = 0
string.sub("40", 1, 1) -- = 4
string.sub("40", 2, 2) -- = 0

You can do this:

s = string.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

But wait, Lua allows some amount of OOP. So you could potentially even do:

z=""
s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

That will work as well and cuts characters.

Now here comes the weird part. You don't even need to assign a string at any point. Simply doing:

s = z.sub
s("50", 1, 1) -- = 5
s("50", 2, 2) -- = 0
s("40", 1, 1) -- = 4
s("40", 2, 2) -- = 0

Will work.


So you can visually see the difference, take a look at the golfed results of this:

Using string.sub (88 characters)

string.sub("50", 1, 1)string.sub("50", 2, 2)string.sub("40", 1, 1)string.sub("40", 2, 2)

Assigning string.sub to a variable (65 characters)

s=string.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

Assigning string.sub using an OOP approach (64 characters)

z=""s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

Assigning string.sub using a.. nil approach? (60 characters)

s=z.sub s("50", 1, 1)s("50", 2, 2)s("40", 1, 1)s("40", 2, 2)

If someone knows why this works, I'd be interested.

\$\endgroup\$
2
  • \$\begingroup\$ The "z.rep" line is breaking on mine. I'm betting there should be a z='' somewhere? A shorter variant of z=''z.rep would just be ('').rep . You can also use the cmdline ... for reading input, and widdle the bytecount down to 57 as follows: z='0'for i=1,...do print(z:rep(i-1)..1 ..z:rep(...-i))end \$\endgroup\$ Mar 22, 2016 at 11:39
  • \$\begingroup\$ I found someone suggesting ("").rep before, but I was unable to get it to work. It'd always error out. Maybe my interpreter is the problem here. I'm struggling to find any documentation on this command line input, do you know where it can be found? \$\endgroup\$
    – Skyl3r
    Mar 23, 2016 at 12:51
6
\$\begingroup\$

Mata, 4 bytes

I(3)

Output

[symmetric]
       1   2   3
    +-------------+
  1 |  1          |
  2 |  0   1      |
  3 |  0   0   1  |
    +-------------+

Mata is the matrix programming language available within the Stata statistical package. I(n) creates an identity matrix of size n*n

\$\endgroup\$
1
  • 6
    \$\begingroup\$ Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a good answer; (ab)use of built-ins is great for golfing. I noticed that your answer is actually 1 byte: I, and the other 3 bytes are just calling the function. That would make your answer one of the lowest on this challenge! :-) \$\endgroup\$
    – wizzwizz4
    Aug 19, 2016 at 10:43
6
+100
\$\begingroup\$

Brain-Flak, 206 170 162 bytes

(([{}])){({}<>(())<><(({})<{({}()(<>)<>)}{}>)>)}{}(({}<><(())>)){({}()<({[()]<({}()<({}<>((((()()()()){}){}){})((()()()()){}){})<>>)>}{})>)<>((()()()()()){})<>}<>

Try it online!

\$\endgroup\$
0
5
\$\begingroup\$

K6, 1 byte

=

= is exactly this

Try it online!

\$\endgroup\$
4
\$\begingroup\$

K, 7 bytes

t=\:t:!

Take the equality cross product of two vectors containing [0,n).

In action:

  t=\:t:!3
(1 0 0
 0 1 0
 0 0 1)
  t=\:t:!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)
\$\endgroup\$
4
\$\begingroup\$

Pyth, 8 bytes

mmsqdkQQ

Try it here.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I must say, it's highly unusual that the Pyth answer is four times longer than the shortest answer... \$\endgroup\$ Jan 28, 2016 at 21:01
  • \$\begingroup\$ Hrm, this was the best I was able to get that looks 100% valid, but I did find qRRQQ which seems to work except you get True and False instead of 1 and 0, however fixing this afaik requires using three bytes for sMM which doesn't help... \$\endgroup\$ Jan 28, 2016 at 21:11
  • \$\begingroup\$ @FryAmTheEggman I also found qRRQQ. I've tried a number of other programs, and none of them were shorter. \$\endgroup\$
    – lirtosiast
    Jan 28, 2016 at 21:12
4
\$\begingroup\$

Mathematica, 14 bytes

IdentityMatrix

Test case

IdentityMatrix[4]
(* {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} *)
\$\endgroup\$
4
\$\begingroup\$

Mathematica, 35 Bytes

without using IdentityMatrix

Table[Boole[i==j],{i,1,#},{j,1,#}]&
\$\endgroup\$
4
\$\begingroup\$

Javascript, 40

f=
n=>'0'.repeat(n).replace(/./g,"$`1$'\n")

I.oninput=_=>O.innerHTML=f(+I.value)
I.oninput()
<input id=I value=5>
<pre id=O>

\$\endgroup\$
4
\$\begingroup\$

Japt, 14 12 10 bytes

Uo £Z®¥X|0

Test it online! Note: this version has a few extra bytes to pretty-print the output.

Uo £Z®¥X|0    // Implicit: U = input integer
Uo £          // Create the range [0..U). Map each item X and the full array Z to:
    Z®        //  Take the full array Z, and map each item Z to:
      ¥X|0    //   (X == Z) converted to a number. 1 for equal, 0 for non-equal.
              // Implicit: output result of last expression
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

05AB1E, 4 bytes

°¨œÙ

Try it online!

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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Nice answer! An alternative is LDδQ, for 4 bytes as well. \$\endgroup\$
    – Mr. Xcoder
    Aug 28, 2018 at 15:16
3
\$\begingroup\$

Java, 60 bytes

n->{int[][]i=new int[n][n];for(;n-->0;)i[n][n]=1;return i;};

Creates a 2D array and replaces elements where row and column are equal with 1.

\$\endgroup\$
1
  • \$\begingroup\$ You don't have to add the trailing semicolon to the byte-count for Java lambda answers. \$\endgroup\$ Jun 29, 2017 at 14:20
3
\$\begingroup\$

CJam, 7 bytes

{,_ff=}

This is a code block that pops an integer from the stack and pushes a 2D array in return.

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.