| Bytes | Lang | Time | Link |
|---|---|---|---|
| 085 | Tcl | 180425T183741Z | sergiol |
| 052 | AWK | 250317T160646Z | xrs |
| 001 | Julia 1.2+LinearAlgebra | 250315T201908Z | MarcMush |
| 003 | Julia 0.6 | 160128T183259Z | Alex A. |
| 092 | OpTeX | 250315T003139Z | jlab |
| 054 | Fortran GFortran | 230529T061012Z | roblogic |
| 003 | Stax | 240828T190905Z | Khuldrae |
| 022 | Ruby rmatrix | 240828T184603Z | Jordan |
| 004 | Uiua | 240525T164154Z | noodle p |
| 003 | Pip | 221202T024650Z | naffetS |
| 045 | Bash w/ coreutils and awk | 170703T142446Z | Xophmeis |
| 383 | Malbolge Unshackled | 231103T085604Z | Kamila S |
| 016 | Kamilalisp | 231001T174353Z | Kamila S |
| 152 | jamforth | 230904T204310Z | allisonl |
| 004 | Itr | 230814T152653Z | bsoelch |
| 202 | TSQL | 230815T040421Z | DanielOn |
| 004 | Thunno 2 | 230607T074046Z | The Thon |
| 003 | Nekomata | 230529T030943Z | alephalp |
| 005 | Pyt | 230213T123823Z | Kip the |
| 036 | Arturo | 230213T114057Z | chunes |
| 004 | Husk | 221203T124735Z | Dominic |
| 001 | K ngn/k | 221203T120523Z | doug |
| 510 | Nibbles | 221203T105212Z | Dominic |
| 006 | Pip P | 221203T072905Z | Aiden Ch |
| 004 | BQN | 221201T220301Z | DLosc |
| 011 | V | 170622T175514Z | DJMcMayh |
| 035 | Knight | 220805T022735Z | 97.100.9 |
| 014 | PARI/GP | 220805T013732Z | alephalp |
| 015 | Factor + math.matrices | 220804T220424Z | chunes |
| 002 | Vyxal | 220804T205148Z | naffetS |
| 007 | Jellyfish | 220804T202205Z | DLosc |
| 011 | APL Dyalog Extended | 210911T064755Z | wasif |
| 114 | D | 190211T122952Z | mdahmoun |
| 048 | Forth gforth | 180828T170849Z | reffu |
| 074 | JavaScript | 160128T184403Z | Conor O& |
| 162 | BrainFlak | 170622T200640Z | Wheat Wi |
| 088 | PHP 88 Bytes | 180828T153054Z | Francisc |
| 004 | 05AB1E | 180828T150845Z | user2956 |
| 006 | 05AB1E | 180828T142743Z | Kevin Cr |
| 092 | Common Lisp | 170904T222052Z | ceilingc |
| 028 | R | 180427T074034Z | Kirill L |
| 031 | R | 180115T193942Z | Giuseppe |
| 007 | Charcoal | 180426T073821Z | ASCII-on |
| 055 | PHP | 180426T024702Z | Titus |
| 010 | Gol><> | 180426T014415Z | Bubbler |
| 015 | Octave | 180425T191327Z | Stewie G |
| 004 | Husk | 180425T185817Z | ბიმო |
| 043 | Excel VBA | 170702T163301Z | Taylor R |
| 037 | Haskell | 160128T214139Z | Sheridan |
| 047 | Vim | 180103T100020Z | Endenite |
| 045 | PowerShell | 170701T211641Z | Andrei O |
| 052 | Python 2 | 170629T200024Z | mdahmoun |
| 026 | Mathematica | 170629T225552Z | ZaMoC |
| 003 | Matlab | 170629T214346Z | EBH |
| 068 | Axiom | 170629T193622Z | user5898 |
| 050 | R | 170629T174149Z | Ivanneke |
| 049 | PHP | 170629T170839Z | Xanderha |
| 045 | Clojure | 170629T145508Z | NikoNyrh |
| 010 | Japt | 160128T194125Z | ETHprodu |
| 107 | tinylisp repl | 170629T063109Z | DLosc |
| 059 | Rust | 170622T183853Z | Censored |
| 064 | PHP | 170329T174539Z | Jör |
| 002 | Jelly | 170622T171629Z | Christia |
| 005 | Samau | 160129T132008Z | alephalp |
| 001 | K6 | 160712T184944Z | Adá |
| 015 | Sage | 160428T040802Z | user4594 |
| 106 | PHP | 160821T181706Z | Kees |
| 320 | picTuring 16 States | 160820T032523Z | KoreanwG |
| 004 | Mata | 160819T094417Z | Guest010 |
| 012 | Jellyfish | 160819T082846Z | Zgarb |
| 024 | Perl | 160308T154240Z | Ton Hosp |
| 040 | Javascript | 160428T030253Z | Washingt |
| 718 | Jolf | 160128T182754Z | Conor O& |
| 033 | Perl | 160128T212154Z | Andreas |
| 005 | PARI/GP | 160203T191205Z | Charles |
| 107 | Python 3 | 160209T174317Z | Argenis |
| 022 | Python 3 | 160203T165810Z | Ogaday |
| 035 | Mathematica | 160129T171433Z | A Simmon |
| 102 | Oracle SQL 11.2 | 160203T203908Z | Jeto |
| 111 | C++ | 160203T200034Z | MegaTom |
| 042 | Ruby | 160203T195612Z | MegaTom |
| 051 | Scala | 160129T043612Z | Jacob |
| 200 | Java | 160202T061205Z | SoloKix |
| 030 | Python 3.5 with NumPy | 160128T195847Z | linkian2 |
| 075 | Mouse | 160129T170854Z | Alex A. |
| 005 | APL | 160128T183845Z | Alex A. |
| 048 | Python 3 | 160128T182430Z | Morgan T |
| 065 | Lua | 160128T190206Z | Skyl3r |
| 036 | 𝔼𝕊𝕄𝕚𝕟 | 160129T000726Z | Mama Fun |
| 014 | Mathematica | 160129T024916Z | njpipeor |
| 5656 | C | 160128T233018Z | Level Ri |
| 038 | Ruby | 160129T000145Z | Level Ri |
| 042 | Python 2 | 160129T000903Z | xnor |
| 035 | Perl 6 | 160128T234336Z | Brad Gil |
| 048 | Ruby | 160128T224837Z | PellMell |
| 024 | Seriously | 160128T223635Z | user4594 |
| 025 | Retina | 160128T200323Z | Digital |
| 007 | Pyth | 160128T221340Z | Jakube |
| 002 | MATL | 160128T183532Z | a spaghe |
| 027 | Haskell | 160128T214958Z | nimi |
| 007 | CJam | 160128T211210Z | Dennis |
| 008 | Pyth | 160128T205849Z | lirtosia |
| 002 | TIBASIC | 160128T191227Z | lirtosia |
| 060 | Java | 160128T204207Z | TNT |
| 052 | JavaScript ES6 | 160128T193551Z | ETHprodu |
| 004 | R | 160128T200812Z | Alex A. |
| 007 | K | 160128T195344Z | JohnE |
| 052 | PowerShell | 160128T194756Z | AdmBorkB |
| 004 | J | 160128T190714Z | marinus |
| 004 | Jelly | 160128T184902Z | Dennis |
| 004 | Octave | 160128T182417Z | a spaghe |
| 054 | Haskell | 160128T182930Z | ThreeFx |
Tcl, 85 bytes
proc I n {time {incr j
time {lappend a [expr [incr i]==$j]} $n
puts $a
unset a i} $n}
AWK, 52 bytes
{for(;i++<$1;print"")for(j=0;j++<$1;)printf(i==j)FS}
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 0.6, 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.
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
Fortran (GFortran), 110 86 62 54 bytes
read*,n;do5 i=1,n
5 print*,(merge(1,0,i==j),j=1,n)
end
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}
Uiua, 4 bytes
⊞=.⇡
Read: ⊞ table of = equality by . two copies of ⇡ the numeric range 0 to the input.
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
yes 0generates an endless stream of0s tostdout;head -$((N*N))takes the first N2 lines;xargs -n$Ngroups every N lines and outputs them together;awk {\$NR=1}1changes the value of the field whose index matches the line number to a1(otherwise it remains0) and then outputs the whole record.
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.
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
¹®0^
using matrix operations, returns a matrix
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)
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
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€=
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
ᵒ-¬
ᵒ- Generate a 2d table with subtraction
¬ Logical not (converts 0 to 1 and other numbers to 0)
Pyt, 5 bytes
řĐɐ=Ɩ
ř implicit input; create řange [1,2,...,n]
Đ Đuplicate
ɐ= for ɐll pairs: are elements equal?
Ɩ cast to Ɩnteger; implicit print
Husk, 4 bytes
´Ṫ=ḣ
´ # 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
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?
Pip -P, 6 bytes
_=BMCa
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
Knight, 35 bytes
;=nP;=i~1W<=i+1i nO S*"0 "n *2i 1 1
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
Takes the zeroth power of the zero matrix.
See also Charles's answer,
Jellyfish, 8 7 bytes
P&O`=ri
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}
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();}}
Forth (gforth), 48 bytes
: f dup 0 do dup 0 do 0 i j = - . loop cr loop ;
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
(([{}])){({}<>(())<><(({})<{({}()(<>)<>)}{}>)>)}{}(({}<><(())>)){({}()<({[()]<({}()<({}<>((((()()()()){}){}){})((()()()()){}){})<>>)>}{})>)<>((()()()()()){})<>}<>
PHP 88 Bytes
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, 6 bytes
Lã€Ësô
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)
R, 28 bytes
function(n,x=1:n)+!x%o%x-x^2
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,"==")
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θ⁼κμ
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.
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|;
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)
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
´Ṫ=ḣ
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
Python 2, 52 bytes
y=x=2**input()
while~-x:x/=2;print str(bin(y+x))[3:]
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))
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
Sage, 15 bytes
identity_matrix
Exactly what it says on the tin
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.
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
iis input, andrcomputes the range from 0 to input-1.- The operator
(is a left hook. On inputs-andR, it appliesR(rotate) to the range and its negated version. This gives thei×imatrix whose rows are the rangesri, rotated k steps to the right for each row k. `Ncomputes 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.Pprints the matrix.
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.
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
Мƕï
I'm finding a lot of these 3-char solutions. It's just a builtin.
Bonus solution, 11 chars / 22 bytes
⩥ïⓜãĉ⇝+($≔a
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
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
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
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.
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.
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.
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.




