44
\$\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
    \$\begingroup\$ Given an integer input n ... -- I assume you mean a natural number? \$\endgroup\$ – Jonathan Frech Aug 28 '18 at 17:00

84 Answers 84

1
\$\begingroup\$

PHP, 64 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Clojure, 45 bytes

#(for[i(range %)](assoc(vec(repeat % 0))i 1))
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Mathematica ,26 bytes

without using IdentityMatrix

Boole[#==#2]&~Array~{#,#}&
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

PowerShell, 45 bytes

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

Try It Online!

\$\endgroup\$
1
\$\begingroup\$

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

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

Usage

Set the N environment variable to the matrix size

$ N=5
$ yes 0|head -$((N*N))|xargs -n$N echo|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 0 generates an endless stream of 0s to stdout;
  • head -$((N*N)) takes the first N2 lines;
  • xargs -n$N echo groups every N lines and outputs them together;
  • awk {\$NR=1}1 changes the value of the field whose index matches the line number to a 1 (otherwise it remains 0) 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...

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Save 1 byte: "=1*(Row()=Column())" \$\endgroup\$ – Engineer Toast Apr 25 '18 at 15:18
1
\$\begingroup\$

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]]
\$\endgroup\$
1
\$\begingroup\$

Tcl, 92 bytes

proc I n {time {incr j;set a "";set i 0;time {lappend a [expr [incr i]==$j]} $n;puts $a} $n}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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]]
\$\endgroup\$
  • 1
    \$\begingroup\$ Alternative 6-byter °¨IF=Á \$\endgroup\$ – Kaldo Aug 28 '18 at 15:01
  • \$\begingroup\$ @Kaldo Ah, that's quite a bit different than my approach, but also pretty cool. And I just saw your 4-byte answer, +1 from me. :) \$\endgroup\$ – Kevin Cruijssen Aug 28 '18 at 15:22
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Why not eta-reduce this to identity_matrix? \$\endgroup\$ – Lynn Aug 21 '16 at 18:21
0
\$\begingroup\$

V, 16, 11 bytes (non-competing?)

Ài0 ÀÄòjl

Try it online!

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

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.

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

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

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

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!

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

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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