g | x | w | all
Bytes Lang Time Link
085Tcl180425T183741Zsergiol
052AWK250317T160646Zxrs
001Julia 1.2+LinearAlgebra250315T201908ZMarcMush
003Julia 0.6160128T183259ZAlex A.
092OpTeX250315T003139Zjlab
054Fortran GFortran230529T061012Zroblogic
003Stax240828T190905ZKhuldrae
022Ruby rmatrix240828T184603ZJordan
004Uiua240525T164154Znoodle p
003Pip221202T024650ZnaffetS
045Bash w/ coreutils and awk170703T142446ZXophmeis
383Malbolge Unshackled231103T085604ZKamila S
016Kamilalisp231001T174353ZKamila S
152jamforth230904T204310Zallisonl
004Itr230814T152653Zbsoelch
202TSQL230815T040421ZDanielOn
004Thunno 2230607T074046ZThe Thon
003Nekomata230529T030943Zalephalp
005Pyt230213T123823ZKip the
036Arturo230213T114057Zchunes
004Husk221203T124735ZDominic
001K ngn/k221203T120523Zdoug
510Nibbles221203T105212ZDominic
006Pip P221203T072905ZAiden Ch
004BQN221201T220301ZDLosc
011V170622T175514ZDJMcMayh
035Knight220805T022735Z97.100.9
014PARI/GP220805T013732Zalephalp
015Factor + math.matrices220804T220424Zchunes
002Vyxal220804T205148ZnaffetS
007Jellyfish220804T202205ZDLosc
011APL Dyalog Extended210911T064755Zwasif
114D190211T122952Zmdahmoun
048Forth gforth180828T170849Zreffu
074JavaScript160128T184403ZConor O&
162BrainFlak170622T200640ZWheat Wi
088PHP 88 Bytes180828T153054ZFrancisc
00405AB1E180828T150845Zuser2956
00605AB1E180828T142743ZKevin Cr
092Common Lisp170904T222052Zceilingc
028R180427T074034ZKirill L
031R180115T193942ZGiuseppe
007Charcoal180426T073821ZASCII-on
055PHP180426T024702ZTitus
010Gol><>180426T014415ZBubbler
015Octave180425T191327ZStewie G
004Husk180425T185817Zბიმო
043Excel VBA170702T163301ZTaylor R
037Haskell160128T214139ZSheridan
047Vim180103T100020ZEndenite
045PowerShell170701T211641ZAndrei O
052Python 2170629T200024Zmdahmoun
026Mathematica170629T225552ZZaMoC
003Matlab170629T214346ZEBH
068Axiom170629T193622Zuser5898
050R170629T174149ZIvanneke
049PHP170629T170839ZXanderha
045Clojure170629T145508ZNikoNyrh
010Japt160128T194125ZETHprodu
107tinylisp repl170629T063109ZDLosc
059Rust170622T183853ZCensored
064PHP170329T174539ZJör
002Jelly170622T171629ZChristia
005Samau160129T132008Zalephalp
001K6160712T184944ZAdá
015Sage160428T040802Zuser4594
106PHP160821T181706ZKees
320picTuring 16 States160820T032523ZKoreanwG
004Mata160819T094417ZGuest010
012Jellyfish160819T082846ZZgarb
024Perl160308T154240ZTon Hosp
040Javascript160428T030253ZWashingt
718Jolf160128T182754ZConor O&
033Perl160128T212154ZAndreas
005PARI/GP160203T191205ZCharles
107Python 3160209T174317ZArgenis
022Python 3160203T165810ZOgaday
035Mathematica160129T171433ZA Simmon
102Oracle SQL 11.2160203T203908ZJeto
111C++160203T200034ZMegaTom
042Ruby160203T195612ZMegaTom
051Scala160129T043612ZJacob
200Java160202T061205ZSoloKix
030Python 3.5 with NumPy160128T195847Zlinkian2
075Mouse160129T170854ZAlex A.
005APL160128T183845ZAlex A.
048Python 3160128T182430ZMorgan T
065Lua160128T190206ZSkyl3r
036𝔼𝕊𝕄𝕚𝕟160129T000726ZMama Fun
014Mathematica160129T024916Znjpipeor
5656C160128T233018ZLevel Ri
038Ruby160129T000145ZLevel Ri
042Python 2160129T000903Zxnor
035Perl 6160128T234336ZBrad Gil
048Ruby160128T224837ZPellMell
024Seriously160128T223635Zuser4594
025Retina160128T200323ZDigital
007Pyth160128T221340ZJakube
002MATL160128T183532Za spaghe
027Haskell160128T214958Znimi
007CJam160128T211210ZDennis
008Pyth160128T205849Zlirtosia
002TIBASIC160128T191227Zlirtosia
060Java160128T204207ZTNT
052JavaScript ES6160128T193551ZETHprodu
004R160128T200812ZAlex A.
007K160128T195344ZJohnE
052PowerShell160128T194756ZAdmBorkB
004J160128T190714Zmarinus
004Jelly160128T184902ZDennis
004Octave160128T182417Za spaghe
054Haskell160128T182930ZThreeFx

Tcl, 85 bytes

proc I n {time {incr j
time {lappend a [expr [incr i]==$j]} $n
puts $a
unset a i} $n}

Try it online!

AWK, 52 bytes

{for(;i++<$1;print"")for(j=0;j++<$1;)printf(i==j)FS}

Attempt This Online!

awk '{for(;i++<$1;print"")for(j=0;j++<$1;)printf(i==j)FS}' <<< 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

Julia 1.2+LinearAlgebra, 1 byte

I

Attempt This Online!

Julia, 15 bytes

!n=(1:n)'.==1:n

Attempt This Online!

Julia 0.6, 9 3 bytes

eye

Try it online!

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.

OpTeX, 92 bytes

\def~#1{$\matrix{\fornum1..#1\do{\fornum2..##1\do{0&}1\fornum##1..\numexpr#1-1\do{&0}\cr}}$}

OpTeX is a modernized version of plain TeX. Of course, the output is better if surrounded with square brackets. But this needs 13 more bytes

\def~#1{$\left[\matrix{\fornum1..#1\do{\fornum2..##1\do{0&}1\fornum##1..\numexpr#1-1\do{&0}\cr}}\right]$}

Test case:

\def~#1{$\left[\matrix{\fornum1..#1\do{\fornum2..##1\do{0&}1\fornum##1..\numexpr#1-1\do{&0}\cr}}\right]$}


~1

\vskip 1em

~3

\vskip 1em

~7


\bye

Example

Fortran (GFortran), 110 86 62 54 bytes

read*,n;do5 i=1,n
5 print*,(merge(1,0,i==j),j=1,n)
end

Try it online! 62b 86b 110b

I finally figured out the ternary operator (merge) in gfortran.

Stax, 3 bytes

cK=

Run and debug it at staxlang.xyz!

Cartesian join of [1..n] with itself by comparison for equality. A neat quirk of K is that it produces a list of rows instead of a flat list, so we have separators!

4 bytes

¡♠αk

Run and debug it at staxlang.xyz!

Unpacked (5 bytes):

1](:)
1]       literal [1]
  (      pad with 0 to width n
   :)    all right rotations

Ruby -rmatrix, 22 bytes

Built-in. Here are a couple more creative Ruby solutions by others without built-ins: 38 bytes, 42 bytes.

->n{Matrix.identity n}

Attempt This Online!

Uiua, 4 bytes

⊞=.⇡

Try it online!

Read: table of = equality by . two copies of the numeric range 0 to the input.

Pip, 3 bytes

EYa

Try It Online!

Builtin.

Bash (w/ coreutils and awk), 51 50 45 bytes

yes 0|head -$((N*N))|xargs -n$N|awk {\$NR=1}1

Usage

Set the N environment variable to the matrix size

$ N=5
$ yes 0|head -$((N*N))|xargs -n$N|awk {\$NR=1}1
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

Explanation

There may be a shorter way to generate N2 lines of 0s, but I haven't found one yet...

Malbolge Unshackled, 1,664,383 bytes.

A link to GitHub as StackExchange does not allow posting answers so long. One of my fastest Malbolge programs.

I(16)

Kamilalisp, 16 bytes

[$(⌼ =) #0 #0]∘⍳

Attempt This Online!

jamforth, 152 bytes

: F DUP DUP 2* 1- DUP ALLOT SWAP DFOR 2DUP + 48 SWAP C! REPEAT TUCK + 1- 49 SWAP C! SWAP TUCK + 1- SWAP DUP DFOR -ROT 2DUP TELL CR -ROT 1- -ROT REPEAT ;

196 bytes compiled, theoretically half that on a 16 bit machine or token threaded forth with 16 bit tokens. F, when called, prints the NxN identity matrix where N is the number on top of the stack.

Here it is deobfuscated:


: POPULATE ( len )
    DUP 2* 1- ( len 2len-1 )
    DUP ALLOT ( len 2len-1 ptr )
    SWAP DFOR
        2DUP + [CHAR] 0 SWAP C!
    REPEAT
    TUCK + 1- [CHAR] 1 SWAP C!
;
: PRINT ( ptr len )
    TUCK + 1- SWAP
    DUP DFOR
        ( ptr len idx )
        -ROT 2DUP TELL CR
        -ROT 1-
        -ROT
    REPEAT
;
: GO DUP POPULATE SWAP PRINT ;

I know I committed to jamforth about 25 minutes before posting this, but I wrote DFOR a few weeks back and just didn't get around to committing it.

Itr, 4 bytes

ºµÍT

using array operations, returns a nested array

online interpreter

¹®0^

using matrix operations, returns a matrix

online interpreter

Explanation

ºµÍT  ; implicit input
º     ; convert to zero-based array
 µÍ   ; replace each element with an array that has a 1 at the specified position
   T  ; transpose to fill in missing zero elements
      ; implicit output
¹®0^ ; implicit input
¹    ; 1-based range
 ®   ; converted to matrix
  0^ ; to the 0th power (matrix implicitly padded with zeros)
     ; implicit output

T-SQL, 202 bytes

DECLARE @s VARCHAR(MAX);SELECT @s='SELECT '+STRING_AGG('CASE WHEN value='+CAST(value AS CHAR)+' THEN 1 ELSE 0 END',',')+' FROM GENERATE_SERIES(1,'+CAST(@n AS CHAR)+')'FROM GENERATE_SERIES(1,@n);EXEC(@s)

dbfiddle

Explanation:

DECLARE @n INT = 5; -- Input integer assigned to the variable @n. Not counted in byte count
DECLARE @s VARCHAR(MAX); -- string variable to house the upcoming dynamic sql

-- dynamically builds a sql query that will have @n many columns and stores it in @s.
SELECT @s='SELECT '+STRING_AGG('CASE WHEN value='+CAST(value AS CHAR)+' THEN 1 ELSE 0 END',',')+' FROM GENERATE_SERIES(1,'+CAST(@n AS CHAR)+')' 
FROM GENERATE_SERIES(1,@n); 
EXEC(@s) -- Executes the string @s as t-sql code.


    --Example, dynamically built query looks like this for @n = 5
    SELECT CASE WHEN value=1                              THEN 1 ELSE 0 END
        ,CASE WHEN value=2                              THEN 1 ELSE 0 END
        ,CASE WHEN value=3                              THEN 1 ELSE 0 END
        ,CASE WHEN value=4                              THEN 1 ELSE 0 END
        ,CASE WHEN value=5                              THEN 1 ELSE 0 END 
    FROM GENERATE_SERIES(1,5                             )
    --Note, white space after integer values due to casting as CHAR. casting as VARCHAR would clean this up but cost an extra 3 bytes per call.

Output for @n=5

enter image description here

Will only work on SQL server 2022 or greater (GENERATE_SERIES needs compatibility level 160 or greater). Likely also work on Azure SQL database etc...

There is already a superior (in terms of byte count) oracle sql answer. But that answer produces a single string column of zeros and ones, whereas this answer produces an n by n table of numeric zeros and ones. So I figured this was different enough to still share.

Thunno 2, 4 bytes

RD€=

Attempt This Online!

Explanation

RD€=  # Implicit input
R     # Push the range [1..n]
  €   # For each number,
   =  # Compare it with
 D    # The range [1..n]
      # Implicit output

Nekomata, 3 bytes

ᵒ-¬

Attempt This Online!

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

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

Arturo, 36 bytes

$=>[unique permutate[1]++@.of:&-1,0]

Try it

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

K (ngn/k), 1 byte

=

Try it online!

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?         

enter image description here

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) 

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

V, 16, 11 bytes

Ài0 ÀÄòjl

Try it online!

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)

PARI/GP, 14 bytes

n->matrix(n)^0

Attempt This Online!

Takes the zeroth power of the zero matrix.

See also Charles's answer,

Factor + math.matrices, 15 bytes

identity-matrix

Try it online!

Vyxal, 2 bytes

Þ□

Try it Online!

Vyxal literally has a builtin for this.

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

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.

D, 114 bytes

void f(int n){import std.stdio;int N=n*n;while(N--){if(N%(n+1))write("0 ");else write("1 ");if(N%n==0)writeln();}}

Try it online!

Forth (gforth), 48 bytes

: f dup 0 do dup 0 do 0 i j = - . loop cr loop ;

Try it online!

Explanation

uses nested loops to output the matrix. For each element it outputs 1 if the indexes are equal, and 0 otherwise.

Code Explanation

:f           \ start a new word definition
  dup        \ duplicate input
  0 do       \ outer counted loop from 0 to input - 1
    dup      \ duplicate input again 
    0 do     \ inner counted loop from 0 to input - 1
      0      \ put a 0 on the stack (used to convert -1 to 1)
      i j =  \ -1 if i equals j, 0 otherwise
      - .    \ subtract from 0 to convert -1 to 1, and output
    loop     \ end inner loop
    cr       \ output a newline
  loop       \ end outer loop
;            \ end word definition

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

Brain-Flak, 206 170 162 bytes

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

Try it online!

PHP 88 Bytes

Try it online

Code

<?php for($i=0;$i++<$argv;){$a=array_fill(1,$argv,0);$a[$i]=1;echo implode(",",$a)."
";}

Explanation

<?php 
  for($i=0;$i++<$argv;){          // loop up to the argument
      $a=array_fill(1,$argv,0);   // create an array fill with 0 with length = $argv value
      $a[$i]=1;                   // use the current iteration to place the "1"
      echo implode(",",$a)."      // implode to output the matrix
     ";}

Output

  $argv=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

05AB1E, 4 bytes

°¨œÙ

Try it online!

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

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]]

Common Lisp, 96 94 92 bytes

(lambda(n)(set'a(make-array(list n n):initial-element 0))(dotimes(i n)(setf(aref a i i)1))a)

Try it online!

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.

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.

Charcoal, 7 bytes

EθEθ⁼κμ

Try it online!

This returns an array, which in Charcoal is not readable in its default format. A version using Wolfram Lists is included below for readability.

Explanation

Eθ       Map for each number from 0 to first input
   Eθ    Map for each number from 0 to first input
      ⁼κμ Return whether both loop indices (yes, indices) are the same. The variables here are: i = first loop variable, k = first loop index, l = second loop variable, m = second loop index.

Readable version
Even accepts input as unary :P

PHP, 55 bytes

while($p**.5<$z=+$argn)echo$p%-~$z?0:1,"
 "[++$p%$z>0];

requires PHP 5.6 or later for the power operator. Note that the second line begins with a space!

Run as pipe with -nR or 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

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.

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]]

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

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

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

PowerShell, 45 bytes

{param($n)0..--$n|%{"$(,0*$_+1+,0*($n-$_))"}}

Try It Online!

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.

Mathematica ,26 bytes

without using IdentityMatrix

Boole[#==#2]&~Array~{#,#}&

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

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

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.

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.

Clojure, 45 bytes

#(for[i(range %)](assoc(vec(repeat % 0))i 1))

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

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

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

PHP, 64 bytes

for(;$i<$argn**2;$m?:$k++)echo$k==$m?:0,($m=++$i%$argn)?" ":"
";

Try it online!

Jelly, 2 bytes

Try it online!

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

K6, 1 byte

=

= is exactly this

Try it online!

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.

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";
    }
?>

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.

loading

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.

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

Jellyfish, 12 bytes

P`N(Rri
   -

Try it online! This entry is non-competing.

Explanation

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

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>

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
    \xad☺   take one argument
         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

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

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.

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)

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.

Mathematica, 35 Bytes

without using IdentityMatrix

Table[Boole[i==j],{i,1,#},{j,1,#}]&

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;

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);}

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.

Scala, 53 51 bytes

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

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?

Python 3.5 with NumPy - 57 49 30 bytes

import numpy
numpy.identity

NumPy.identity takes in an integer, n, and returns a n by n identity matrix. This answer is allowable via this policy.

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:
)
$

APL, 5 bytes

∘.=⍨⍳

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

Try it here

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

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.

𝔼𝕊𝕄𝕚𝕟, 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

Mathematica, 14 bytes

IdentityMatrix

Test case

IdentityMatrix[4]
(* {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}} *)

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);}

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

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

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" }

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

Seriously, 24 bytes

,;╗r`╙k╜#"{:0%sb}"%f#`MR

Try it online!

Explanation:

,;╗r`╙k╜#"{:0%sb}"%f#`MR
,;╗                       get input (n), save a copy in register 0
   r                      push [0..n-1]
    `                `M   map the function:
     ╙k                     push [2**a]
       ╜#"{:0%sb}"%         push "{:0nb}"
                   f#       format and explode string
                            (push binary representation, padded with zeroes to n digits)
                       R  reverse list

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.

Pyth, 7 bytes

XRm0Q1Q

Try it online: Demonstration

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

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

Haskell, 27 bytes

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 )

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!

Pyth, 8 bytes

mmsqdkQQ

Try it here.

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.

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.

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.

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

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)

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

J, 4 bytes

=@i.

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

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.

Octave, 10 4 bytes

@eye

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

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.