# Construct the Identity Matrix

The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.


This is , so the shortest code in bytes wins.

• Given an integer input n ... -- I assume you mean a natural number? Commented Aug 28, 2018 at 17:00

# 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


# 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

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.

# 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


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

# Kamilalisp, 16 bytes

[$(⌼ =) #0 #0]∘⍳  Attempt This Online! ## 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. • Babe wake up new Malbolge program just dropped Commented Nov 3, 2023 at 11:29 ## 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  # 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.

# Charcoal, 7 bytes

ＥθＥθ⁼κμ


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

Ｅθ       Map for each number from 0 to first input
Ｅθ    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.


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

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


# 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


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

# PARI/GP, 14 bytes

n->matrix(n)^0

Attempt This Online!

Takes the zeroth power of the zero matrix.

# V, 16, 11 bytes

Ài0 ÀÄòjl


Try it online!

# Pip, 3 bytes

EYa


Try It Online!

Builtin.

• What's the shortest non-builtin solution you can find? Commented Dec 2, 2022 at 16:31
• @DLosc I found a non-builtin solution of 6 bytes. Commented Dec 3, 2022 at 7:29

# Uiua, 4 bytes

⊞=.⇡


Try it online!

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