I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# Identity matrix

Identity matrix
You are encouraged to solve this task according to the task description, using any language you may know.

Build an   identity matrix   of a size known at run-time.

An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).

${\displaystyle I_{n}={\begin{bmatrix}1&0&0&\cdots &0\\0&1&0&\cdots &0\\0&0&1&\cdots &0\\\vdots &\vdots &\vdots &\ddots &\vdots \\0&0&0&\cdots &1\\\end{bmatrix}}}$

## 11l

Translation of: Python
F identity_matrix(size)   V matrix = [[0] * size] * size   L(i) 0 .< size      matrix[i][i] = 1   R matrix L(row) identity_matrix(3)   print(row)
Output:
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]


## 360 Assembly

*        Identity matrix           31/03/2017INDENMAT CSECT         USING  INDENMAT,R13       base register         B      72(R15)            skip savearea         DC     17F'0'             savearea         STM    R14,R12,12(R13)    save previous context         ST     R13,4(R15)         link backward         ST     R15,8(R13)         link forward         LR     R13,R15            set addressability         L      R1,N               n         MH     R1,N+2             n*n         SLA    R1,2               *4         ST     R1,LL              amount of storage required         GETMAIN RU,LV=(R1)        allocate storage for matrix         USING  DYNA,R11           make storage addressable         LR     R11,R1             set addressability         LA     R6,1               i=1       DO WHILE=(C,R6,LE,N)        do i=1 to n         LA     R7,1                 j=1       DO WHILE=(C,R7,LE,N)          do j=1 to n       IF CR,R6,EQ,R7 THEN             if i=j then         LA     R2,1                     k=1       ELSE     ,                      else         LA     R2,0                     k=0       ENDIF    ,                      endif         LR     R1,R6                  i         BCTR   R1,0                   -1         MH     R1,N+2                 *n         AR     R1,R7                  (i-1)*n+j         BCTR   R1,0                   -1         SLA    R1,2                   *4         ST     R2,A(R1)               a(i,j)=k         LA     R7,1(R7)               j++       ENDDO    ,                    enddo j         LA     R6,1(R6)             i++       ENDDO    ,                  enddo i         LA     R6,1               i=1       DO WHILE=(C,R6,LE,N)        do i=1 to n         LA     R10,PG               pgi=0         LA     R7,1                 j=1       DO WHILE=(C,R7,LE,N)          do j=1 to n         LR     R1,R6                  i         BCTR   R1,0                   -1         MH     R1,N+2                 *n         AR     R1,R7                  (i-1)*n+j         BCTR   R1,0                   -1         SLA    R1,2                   *4         L      R2,A(R1)               a(i,j)         XDECO  R2,XDEC                edit         MVC    0(1,R10),XDEC+11       output         LA     R10,1(R10)             pgi+=1         LA     R7,1(R7)               j++       ENDDO    ,                    enddo j         XPRNT  PG,L'PG              print         LA     R6,1(R6)             i++       ENDDO    ,                  enddo i         LA     R1,A               address to free         LA     R2,LL              amount of storage to free         FREEMAIN A=(R1),LV=(R2)   free allocated storage         DROP   R11                drop register         L      R13,4(0,R13)       restore previous savearea pointer         LM     R14,R12,12(R13)    restore previous context         XR     R15,R15            rc=0         BR     R14                exitNN       EQU    10                 parameter n  (90=>32K)N        DC     A(NN)              nLL       DS     F                  n*n*4PG       DC     CL(NN)' '          bufferXDEC     DS     CL12               tempDYNA     DSECTA        DS     F                  a(n,n)         YREGS         END    INDENMAT
Output:
1000000000
0100000000
0010000000
0001000000
0000100000
0000010000
0000001000
0000000100
0000000010
0000000001


## Action!

### QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
Translation of: IS-BASIC
SUB inicio(identity())    FOR i = LBOUND(identity,1) TO UBOUND(identity,1)        FOR j = LBOUND(identity,2) TO UBOUND(identity,2)            LET identity(i,j) = 0        NEXT j        LET identity(i,i) = 1    NEXT iEND SUB SUB mostrar(identity())    FOR i = LBOUND(identity,1) TO UBOUND(identity,1)        FOR j = LBOUND(identity,2) TO UBOUND(identity,2)            PRINT identity(i,j);        NEXT j        PRINT    NEXT iEND SUB DO    INPUT "Enter size of matrix "; nLOOP UNTIL n > 0 DIM identity(1 TO n, 1 TO n) CALL inicio(identity())CALL mostrar(identity())

### BASIC256

Translation of: FreeBASIC
arraybase 1do    input "Enter size of matrix: ", nuntil n > 0 dim identity(n, n) fill 0  #we fill everything with 0 # enter 1s in diagonal elementsfor i =  1 to n    identity[i, i] = 1next i # print identity matrix if n < 40print if n < 40 then    for i = 1 to n        for j = 1 to n            print identity[i, j];        next j        print    next ielse    print "Matrix is too big to display on 80 column console"end if
Output:
Same as FreeBASIC entry.

### Yabasic

Translation of: FreeBASIC
repeat    input "Enter size of matrix: " nuntil n > 0  dim identity(n, n) // all zero by default // enter 1s in diagonal elementsfor i =  1 to n    identity(i, i) = 1next i // print identity matrix if n < 40 print if n < 40 then    for i = 1 to n        for j = 1 to n            print identity(i, j);         next j        print    next ielse     print "Matrix is too big to display on 80 column console"end if
Output:
Same as FreeBASIC entry.

## ATS

 (* ****** ****** *)//// How to compile://// patscc -DATS_MEMALLOC_LIBC -o idmatrix idmatrix.dats//(* ****** ****** *)//#include"share/atspre_staload.hats"//(* ****** ****** *) externfunidmatrix{n:nat}(n: size_t(n)): matrixref(int, n, n)implementidmatrix(n) =matrixref_tabulate_cloref<int> (n, n, lam(i, j) => bool2int0(i = j)) (* ****** ****** *) implementmain0 () ={//val N = 5//val M = idmatrix(i2sz(N))val () = fprint_matrixref_sep (stdout_ref, M, i2sz(N), i2sz(N), " ", "\n")val () = fprint_newline (stdout_ref)//} (* end of [main0] *)

## AutoHotkey

msgbox % Clipboard := I(6)return I(n){    r := "--n" , s := " "    loop % n    {        k := A_index , r .= "|  "        loop % n            r .= A_index=k ? "1, " : "0, "        r := RTrim(r, " ,") , r .= "  |n"    }    loop % 4*n        s .= " "    return Rtrim(r,"n") "n" s "--"}
Output:
--
|  1, 0, 0, 0, 0, 0  |
|  0, 1, 0, 0, 0, 0  |
|  0, 0, 1, 0, 0, 0  |
|  0, 0, 0, 1, 0, 0  |
|  0, 0, 0, 0, 1, 0  |
|  0, 0, 0, 0, 0, 1  |
--


 # syntax: GAWK -f IDENTITY_MATRIX.AWK sizeBEGIN {    size = ARGV[1]    if (size !~ /^[0-9]+$/) { print("size invalid or missing from command line") exit(1) } for (i=1; i<=size; i++) { for (j=1; j<=size; j++) { x = (i == j) ? 1 : 0 printf("%2d",x) # print arr[i,j] = x # build } printf("\n") } exit(0)}  Output: for command: GAWK -f IDENTITY_MATRIX.AWK 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  ## Bash  for i in seq$1;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
Output:
for command: ./scriptname 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


## BBC BASIC

      INPUT "Enter size of matrix: " size%      PROCidentitymatrix(size%, im())      FOR r% = 0 TO size%-1        FOR c% = 0 TO size%-1          PRINT im(r%, c%),;        NEXT        PRINT      NEXT r%      END       DEF PROCidentitymatrix(s%, RETURN m())      LOCAL i%      DIM m(s%-1, s%-1)      FOR i% = 0 TO s%-1        m(i%,i%) = 1      NEXT      ENDPROC

beads 1 program 'Identity matrix' var	id : array^2 of num	n = 5 calc main_init	loop from:1 to:n index:i		loop from:1 to:n index:j			id[i,j] = 1 if i == j else 0
Output:
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


## Burlesque

Neither very elegant nor short but it'll do

 blsq ) 6 -.^^0\/[email protected]\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp1 0 0 0 0 00 1 0 0 0 00 0 1 0 0 00 0 0 1 0 00 0 0 0 1 00 0 0 0 0 1

The example above uses strings to generate the identity matrix. If you need a matrix with real numbers (Integers) then use:

 6hd0bx#a.*\[#a.*0#[email protected]{(D!)\/1\/^^bx\/[+}m[e!

Shorter alternative:

 blsq ) 6 ^^^^10\/**XXcy\/co.+sp

## BQN

⍝ Using tableEye ← =⌜˜∘↕•Show Eye 3 ⍝ Using reshapeEye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0}Eye1 5
┌─       ╵ 1 0 0    0 1 0    0 0 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              ┘

Eye generates an identity matrix using a table of equality for [0,n).

Eye1 reshapes a boolean vector to generate the matrix.

## C

 #include <stdlib.h>#include <stdio.h>int main(int argc, char** argv) {   if (argc < 2) {      printf("usage: identitymatrix <number of rows>\n");      exit(EXIT_FAILURE);   }   int rowsize = atoi(argv[1]);   if (rowsize < 0) {      printf("Dimensions of matrix cannot be negative\n");      exit(EXIT_FAILURE);   }   int numElements = rowsize * rowsize;   if (numElements < rowsize) {      printf("Squaring %d caused result to overflow to %d.\n", rowsize, numElements);      abort();   }   int** matrix = calloc(numElements, sizeof(int*));   if (!matrix) {      printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int*));      abort();   }   for (unsigned int row = 0;row < rowsize;row++) {      matrix[row] = calloc(numElements, sizeof(int));      if (!matrix[row]) {         printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int));         abort();      }      matrix[row][row] = 1;   }   printf("Matrix is: \n");   for (unsigned int row = 0;row < rowsize;row++) {      for (unsigned int column = 0;column < rowsize;column++) {         printf("%d ", matrix[row][column]);      }      printf("\n");   }}

## C#

 using System;using System.Linq; namespace IdentityMatrix{    class Program    {        static void Main(string[] args)        {            if (args.Length != 1)            {                Console.WriteLine("Requires exactly one argument");                return;            }            int n;            if (!int.TryParse(args[0], out n))            {                Console.WriteLine("Requires integer parameter");                return;            }             var identity =                Enumerable.Range(0, n).Select(i => Enumerable.Repeat(0, n).Select((z,j) => j == i ? 1 : 0).ToList()).ToList();            foreach (var row in identity)            {                foreach (var elem in row)                {                    Console.Write(" " + elem);                }                Console.WriteLine();            }            Console.ReadKey();        }    }}
Output:
 1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1


## C++

Library: STL
template<class T>class matrix{public:    matrix( unsigned int nSize ) :       m_oData(nSize * nSize, 0), m_nSize(nSize) {}       inline T& operator()(unsigned int x, unsigned int y)      {          return m_oData[x+m_nSize*y];      }       void identity()      {          int nCount = 0;          int nStride = m_nSize + 1;          std::generate( m_oData.begin(), m_oData.end(),               [&]() { return !(nCount++%nStride); } );      }       inline unsigned int size() { return m_nSize; } private:    std::vector<T>    m_oData;    unsigned int      m_nSize;}; int main(){    int nSize;    std::cout << "Enter matrix size (N): ";    std::cin >> nSize;     matrix<int> oMatrix( nSize );     oMatrix.identity();     for ( unsigned int y = 0; y < oMatrix.size(); y++ )    {        for ( unsigned int x = 0; x < oMatrix.size(); x++ )        {            std::cout << oMatrix(x,y) << " ";        }        std::cout << std::endl;    }    return 0;}
Library: boost
 #include <boost/numeric/ublas/matrix.hpp> int main(){    using namespace boost::numeric::ublas;     int nSize;    std::cout << "Enter matrix size (N): ";    std::cin >> nSize;     identity_matrix<int> oMatrix( nSize );     for ( unsigned int y = 0; y < oMatrix.size2(); y++ )    {        for ( unsigned int x = 0; x < oMatrix.size1(); x++ )        {            std::cout << oMatrix(x,y) << " ";        }        std::cout << std::endl;    }     return 0;}
Output:
Enter matrix size (N): 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


## Clio

fn identity-matrix n:  [0:n] -> * fn i:    [0:n] -> * if = i: 1                 else: 0 5 -> identity-matrix -> * print

## Clojure

Translation of: PicoLisp

The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g.

 '( (0 1) (2 3) )

, then care to remove the vec function.

(defn identity-matrix [n]  (let [row (conj (repeat (dec n) 0) 1)]    (vec      (for [i (range 1 (inc n))]        (vec           (reduce conj (drop i row ) (take i row)))))))
Output:
=> (identity-matrix 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]]

The following is a more idomatic definition that utilizes infinite lists and cycling.

 (defn identity-matrix [n]  (take n     (partition n (dec n)                          (cycle (conj (repeat (dec n) 0) 1)))))

## Common Lisp

Common Lisp provides multi-dimensional arrays.

(defun make-identity-matrix (n)  (let ((array (make-array (list n n) :initial-element 0)))    (loop for i below n do (setf (aref array i i) 1))    array))
Output:
* (make-identity-matrix 5)
#2A((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))

(defun identity-matrix (n)  (loop for a from 1 to n        collect (loop for e from 1 to n                       if (= a e) collect 1                      else collect 0)))
Output:
> (identity-matrix 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))


## Component Pascal

BlackBox Component Builder

 MODULE Algebras;IMPORT StdLog,Strings; TYPE	Matrix = POINTER TO ARRAY OF ARRAY OF INTEGER; PROCEDURE NewIdentityMatrix(n: INTEGER): Matrix;VAR	m: Matrix;	i: INTEGER;BEGIN	NEW(m,n,n);	FOR i := 0 TO n - 1 DO		m[i,i] := 1;	END;	RETURN m;END NewIdentityMatrix; PROCEDURE Show(m: Matrix);VAR	i,j: INTEGER;BEGIN	FOR i := 0 TO LEN(m,0) - 1 DO		FOR j := 0 TO LEN(m,1) - 1 DO			StdLog.Int(m[i,j]);		END;		StdLog.Ln	ENDEND Show; PROCEDURE Do*;BEGIN	Show(NewIdentityMatrix(5));END Do;END Algebras.

Execute: ^Q Algebras.Do

Output:
 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


## D

import std.traits; T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {    auto Id = new T[][](n, n);     foreach (r, row; Id) {        static if (__traits(compiles, {row[] = 0;})) {            row[] = 0; // vector op doesn't work with T = BigInt            row[r] = 1;        } else {            foreach (c; 0 .. n)                row[c] = (c == r) ? 1 : 0;        }    }     return Id;} void main() {    import std.stdio, std.bigint;    enum form = "[%([%(%s, %)],\n %)]]";     immutable id1 = matId!real(5);    writefln(form ~ "\n", id1);     immutable id2 = matId!BigInt(3);    writefln(form ~ "\n", id2);     // auto id3 = matId!(const int)(2); // cant't compile}
Output:
[[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, 0, 0],
[0, 1, 0],
[0, 0, 1]]

## Euler Math Toolbox

 function IdentityMatrix(n)  $X:=zeros(n,n);$  for i=1 to n   $X[i,i]:=1;$  end;  $return X;$endfunction
 >function IdentityMatrix (n:index)$return setdiag(zeros(n,n),0,1);$endfunction
 >id(5)

## Excel

### LAMBDA

Excel can lift functions over scalar values to functions over two-dimensional arrays.

Here we bind the name IDMATRIX to a lambda expression in the Name Manager of the Excel WorkBook:

IDMATRIX=LAMBDA(n,    LET(        ixs, SEQUENCE(n, n, 0, 1),        x, MOD(ixs, n),        y, QUOTIENT(ixs, n),         IF(x = y,            1,            0        )    ))
Output:

The formula in cell B2 below populates the B2:F6 grid:

 =IDMATRIX(A2) fx A B C D E F 1 N Identity matrix 2 5 1 0 0 0 0 3 0 1 0 0 0 4 0 0 1 0 0 5 0 0 0 1 0 6 0 0 0 0 1 7 8 3 1 0 0 9 0 1 0 10 0 0 1

## F#

Builds a 2D matrix with the given square size.

 let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0)
Output:
 ident 10;;val it : int [,] = [[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]]

## Factor

Works with: Factor version 0.99 2020-07-03
USING: math.matrices prettyprint ; 6 <identity-matrix> .
Output:
{
{ 1 0 0 0 0 0 }
{ 0 1 0 0 0 0 }
{ 0 0 1 0 0 0 }
{ 0 0 0 1 0 0 }
{ 0 0 0 0 1 0 }
{ 0 0 0 0 0 1 }
}

## FBSL

FBSL's BASIC layer can easily manipulate square matrices of arbitrary sizes and data types in ways similar to e.g. BBC BASIC or OxygenBasic as shown elsewhere on this page. But FBSL has also an extremely fast built-in single-precision vector2f/3f/4f, plane4f, quaternion4f, and matrix4f math library totaling 150 functions and targeting primarily 3D rendering tasks:

 #APPTYPE CONSOLE TYPE M4F ' Matrix 4F m11 AS SINGLE m12 AS SINGLE m13 AS SINGLE m14 AS SINGLE m21 AS SINGLE m22 AS SINGLE m23 AS SINGLE m24 AS SINGLE m31 AS SINGLE m32 AS SINGLE m33 AS SINGLE m34 AS SINGLE m41 AS SINGLE m42 AS SINGLE m43 AS SINGLE m44 AS SINGLE END TYPE DIM m AS M4F ' DIM zeros out any variable automatically PRINT "Matrix 'm' is identity: ", IIF(MATRIXISIDENTITY(@m), "TRUE", "FALSE") ' is matrix an identity? MATRIXIDENTITY(@m) ' set matrix to identity PRINT "Matrix 'm' is identity: ", IIF(MATRIXISIDENTITY(@m), "TRUE", "FALSE") ' is matrix an identity? PAUSE 
Output:
 Matrix 'm' is identity: FALSE Matrix 'm' is identity: TRUE Press any key to continue... 

## Fermat

 Func Identity(n)=Array id[n,n];[id]:=[1]. Identity(7)[id]
Output:
[[  1,  0,  0,  0,  0,  0,  0,
0,  1,  0,  0,  0,  0,  0, 
0,  0,  1,  0,  0,  0,  0,
0,  0,  0,  1,  0,  0,  0, 
0,  0,  0,  0,  1,  0,  0,
0,  0,  0,  0,  0,  1,  0, 
0,  0,  0,  0,  0,  0,  1   ]]

## Forth

Works with: gforth version 0.7.9_20170308
S" fsl-util.fs" REQUIRED : build-identity ( 'p n -- 'p )  \ make an NxN identity matrix  0 DO    I 1+ 0 DO      I J = IF  1.0E0 DUP I J }} F!      ELSE        0.0E0 DUP J I }} F!        0.0E0 DUP I J }} F!      THEN    LOOP  LOOP ; 6 6 float matrix a{{a{{ 6 build-identity6 6 a{{ }}fprint

## Fortran

Works with: Fortran version 95
 program identitymatrix   real, dimension(:, :), allocatable :: I  character(len=8) :: fmt  integer :: ms, j   ms = 10   ! the desired size   allocate(I(ms,ms))  I = 0                           ! Initialize the array.  forall(j = 1:ms) I(j,j) = 1     ! Set the diagonal.   ! I is the identity matrix, let's show it:   write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'  ! if you consider to have used the (row, col) convention,   ! the following will print the transposed matrix (col, row)  ! but I' = I, so it's not important here    write (*, fmt) I(:,:)   deallocate(I) end program identitymatrix

### Notorious trick

The objective is to do the assignment in one fell swoop, rather than separately setting the 0 values and the 1 values. It works because, with integer arithmetic, the only way that both i/j and j/i are one is when they are equal - thus one on the diagonal elements, and zero elsewhere because either i < j so that i/j = 0, or i > j so that j/i = 0. While this means two divides and a multiply per element instead of simply transferring a constant, the constraint on speed is likely to be the limited bandwidth from cpu to memory. The expression's code would surely fit in the cpu's internal memory, and registers would be used for the variables.

      Program Identity      Integer N      Parameter (N = 666)      Real A(N,N)      Integer i,j       ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i)       END

The ForAll statement is a feature of F90, and carries the implication that the assignments may be done in any order, even "simultaneously" (as with multiple cpus), plus that all RHS values are calculated before any LHS part receives a value - not relevant here since the RHS makes no reference to items altered in the LHS. Earlier Fortran compilers lack this statement and so one must use explicit DO-loops:

      DO 1 I = 1,N        DO 1 J = 1,N    1     A(I,J) = (I/J)*(J/I)

Array assignment statements are also a feature of F90 and later.

An alternative might be a simpler logical expression testing i = j except that the numerical values for true and false on a particular system may well not be 1 and 0 but (for instance, via Compaq F90/95 on Windows XP) 0 and -1 instead. On an IBM 390 mainframe, pl/i and Fortran used different values. The Burroughs 6700 inspected the low-order bit only, with the intriguing result that odd integers would be deemed true and even false. Integer arithmetic can't be relied upon across languages either, because in pl/i, integer division doesn't truncate.

## FreeBASIC

' FB 1.05.0 Win64 Dim As Integer n Do  Input "Enter size of matrix "; nLoop Until n > 0  Dim identity(1 To n, 1 To n) As Integer '' all zero by default ' enter 1s in diagonal elementsFor i As Integer =  1 To n  identity(i, i) = 1Next ' print identity matrix if n < 40 Print If n < 40 Then  For i As Integer = 1 To n    For j As Integer = 1 To n      Print identity(i, j);     Next j    Print  Next iElse   Print "Matrix is too big to display on 80 column console"End If PrintPrint "Press any key to quit"Sleep

Sample input/output

Output:
Enter size of matrix ? 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


## Frink

This does not use the Matrix.frink library, which has methods to create an identity matrix, but shows how to build a "raw" identity matrix as a two-dimensional array, and shows how to nicely format it using built-in routines.

n = parseInt[input["Enter matrix dimension as an integer: "]]println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]
Output:
Enter matrix dimension as an integer:  3
┌       ┐
│1  0  0│
│       │
│0  1  0│
│       │
│0  0  1│
└       ┘


## FunL

def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 ) println( identity(3) )
Output:
((1, 0, 0), (0, 1, 0), (0, 0, 1))


## Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website, However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.

## FutureBasic

 include "NSLog.incl" local fn IdentityMatrix( n as NSInteger ) as CFStringRefNSInteger i, jCFMutableArrayRef tempArr = fn MutableArrayWithCapacity( n )CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 ) for i = 0 to n - 1MutableArrayRemoveAllObjects( tempArr )for j = 0 to n - 1MutableArrayInsertObjectAtIndex( tempArr, @"0", j )nextMutableArrayReplaceObjectAtIndex( tempArr, @"1", i )MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) )MutableStringAppendString( mutStr, @"\n" )nextend fn = fn StringWithString( mutStr ) NSLog( @"3:\n%@", fn IdentityMatrix( 3 ) )NSLog( @"5:\n%@", fn IdentityMatrix( 5 ) )NSLog( @"7:\n%@", fn IdentityMatrix( 7 ) )NSLog( @"9:\n%@", fn IdentityMatrix( 9 ) ) HandleEvents
Output:
3:
1 0 0
0 1 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

7:
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1

9:
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1


## GAP

# Built-inIdentityMat(3); # One can also specify the base ringIdentityMat(3, Integers mod 10);

## Go

### Library gonum/mat

package main import (    "fmt"     "gonum.org/v1/gonum/mat") func eye(n int) *mat.Dense {    m := mat.NewDense(n, n, nil)    for i := 0; i < n; i++ {        m.Set(i, i, 1)    }    return m} func main() {    fmt.Println(mat.Formatted(eye(3)))}
Output:
⎡1  0  0⎤
⎢0  1  0⎥
⎣0  0  1⎦


### Library go.matrix

A somewhat earlier matrix library for Go.

package main import (    "fmt"     mat "github.com/skelterjohn/go.matrix") func main() {    fmt.Println(mat.Eye(3))}
Output:
{1, 0, 0,
0, 1, 0,
0, 0, 1}


### From scratch

Simplest: A matrix as a slice of slices, allocated separately.

package main import "fmt" func main() {    fmt.Println(I(3))} func I(n int) [][]float64 {    m := make([][]float64, n)    for i := 0; i < n; i++ {        a := make([]float64, n)        a[i] = 1        m[i] = a    }    return m}
Output:

No special formatting method used.

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


2D, resliced: Representation as a slice of slices still, but with all elements based on single underlying slice. Might save a little memory management, might have a little better locality.

package main import "fmt" func main() {    fmt.Println(I(3))} func I(n int) [][]float64 {    m := make([][]float64, n)    a := make([]float64, n*n)    for i := 0; i < n; i++ {        a[i] = 1        m[i] = a[:n]        a = a[n:]    }    return m}
Output:

Same as previous.

Flat: Representation as a single flat slice. You just have to know to handle it as a square matrix. In many cases that's not a problem and the code is simpler this way. If you want to add a little bit of type checking, you can define a matrix type as shown here.

package main import "fmt" type matrix []float64 func main() {    n := 3    m := I(n)    // dump flat represenation    fmt.Println(m)     // function x turns a row and column into an index into the    // flat representation.    x := func(r, c int) int { return r*n + c }     // access m by row and column.    for r := 0; r < n; r++ {        for c := 0; c < n; c++ {            fmt.Print(m[x(r, c)], " ")        }        fmt.Println()    }} func I(n int) matrix {    m := make(matrix, n*n)    // a fast way to initialize the flat representation    n++    for i := 0; i < len(m); i += n {        m[i] = 1    }    return m}
Output:
[1 0 0 0 1 0 0 0 1]
1 0 0
0 1 0
0 0 1


## Groovy

Solution:

def makeIdentityMatrix = { n ->    (0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }}

Test:

(2..6).each { order ->    def iMatrix = makeIdentityMatrix(order)    iMatrix.each { println it }    println()}
Output:
[1, 0]
[0, 1]

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

[1, 0, 0, 0]
[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 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]

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

## Jsish

/* Identity matrix, in Jsish */function identityMatrix(n) {    var mat = new Array(n).fill(0);    for (var r in mat) {        mat[r] = new Array(n).fill(0);        mat[r][r] = 1;    }    return mat;} provide('identityMatrix', 1); if (Interp.conf('unitTest')) {;    identityMatrix(0);;    identityMatrix(1);;    identityMatrix(2);;    identityMatrix(3);    var mat = identityMatrix(4);    for (var r in mat) puts(mat[r]);} /*=!EXPECTSTART!=identityMatrix(0) ==> []identityMatrix(1) ==> [ [ 1 ] ]identityMatrix(2) ==> [ [ 1, 0 ], [ 0, 1 ] ]identityMatrix(3) ==> [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ][ 1, 0, 0, 0 ][ 0, 1, 0, 0 ][ 0, 0, 1, 0 ][ 0, 0, 0, 1 ]=!EXPECTEND!=*/
Output:

## OCaml

From the interactive loop (that we call the "toplevel"):

$ocaml # let make_id_matrix n = let m = Array.make_matrix n n 0.0 in for i = 0 to pred n do m.(i).(i) <- 1.0 done; (m) ;;val make_id_matrix : int -> float array array = <fun> # make_id_matrix 4 ;;- : float array array =[| [|1.; 0.; 0.; 0.|]; [|0.; 1.; 0.; 0.|]; [|0.; 0.; 1.; 0.|]; [|0.; 0.; 0.; 1.|] |] another way: # let make_id_matrix n = Array.init n (fun i -> Array.init n (fun j -> if i = j then 1.0 else 0.0)) ;;val make_id_matrix : int -> float array array = <fun> # make_id_matrix 4 ;;- : float array array =[| [|1.; 0.; 0.; 0.|]; [|0.; 1.; 0.; 0.|]; [|0.; 0.; 1.; 0.|]; [|0.; 0.; 0.; 1.|] |] When we write a function in the toplevel, it returns us its signature (the prototype), and when we write a variable (or a function call), it returns its type and its value. ## Octave The eye function create the identity (I) matrix, e.g.: I = eye(10) ## Ol  (define (make-identity-matrix n) (map (lambda (i) (append (repeat 0 i) '(1) (repeat 0 (- n i 1)))) (iota n))) (for-each print (make-identity-matrix 3))(for-each print (make-identity-matrix 17)) Output: (1 0 0) (0 1 0) (0 0 1) (1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0) (0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0) (0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0) (0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0) (0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0) (0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0) (0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0) (0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0) (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0) (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1) ## ooRexx ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays.  say "a 3x3 identity matrix"saycall printMatrix createIdentityMatrix(3)saysay "a 5x5 identity matrix"saycall printMatrix createIdentityMatrix(5) ::routine createIdentityMatrix use arg size matrix = .array~new(size, size) loop i = 1 to size loop j = 1 to size if i == j then matrix[i, j] = 1 else matrix[i, j] = 0 end j end i return matrix ::routine printMatrix use arg matrix loop i = 1 to matrix~dimension(1) line = "" loop j = 1 to matrix~dimension(2) line = line matrix[i, j] end j say line end i  Output: a 3x3 identity matrix 1 0 0 0 1 0 0 0 1 a 5x5 identity matrix 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  ## OxygenBasic  Class SquareMatrix'================= double *Cell sys size method SetIdentity() indexbase 0 sys e,i,j e=size*size for i=0 to <size cell(i*size+j)=1 : j++ next end method method constructor(sys n) @cell=getmemory n*n*sizeof double size=n end method method destructor() freememory @cell end method end class new SquareMatrix M(8)M.SetIdentity'...del M  ## PARI/GP Built-in: matid(9) Custom: matrix(9,9,i,j,i==j) ## Pascal program IdentityMatrix(input, output); var matrix: array of array of integer; n, i, j: integer; begin write('Size of matrix: '); readln(n); setlength(matrix, n, n); for i := 0 to n - 1 do matrix[i,i] := 1; for i := 0 to n - 1 do begin for j := 0 to n - 1 do write (matrix[i,j], ' '); writeln; end;end. Output: % ./IdentityMatrix Size of matrix: 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  ## Perl use strict;use warnings;use feature 'say'; sub identity_matrix { my($n) = shift() - 1;    map { [ (0) x $_, 1, (0) x ($n - $_) ] } 0..$n} for (<4 5 6>) {  say "\n$_:"; say join ' ', @$_ for identity_matrix $_;} Output: 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 6: 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 ## Phix function identity(integer n) sequence res = repeat(repeat(0,n),n) for i=1 to n do res[i][i] = 1 end for return res end function ppOpt({pp_Nest,1}) pp(identity(3)) pp(identity(5)) pp(identity(7)) pp(identity(9))  Output: {{1,0,0}, {0,1,0}, {0,0,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}}  {{1,0,0,0,0,0,0}, {0,1,0,0,0,0,0}, {0,0,1,0,0,0,0}, {0,0,0,1,0,0,0}, {0,0,0,0,1,0,0}, {0,0,0,0,0,1,0}, {0,0,0,0,0,0,1}}  {{1,0,0,0,0,0,0,0,0}, {0,1,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,0,0}, {0,0,0,1,0,0,0,0,0}, {0,0,0,0,1,0,0,0,0}, {0,0,0,0,0,1,0,0,0}, {0,0,0,0,0,0,1,0,0}, {0,0,0,0,0,0,0,1,0}, {0,0,0,0,0,0,0,0,1}}  ## PHP  function identity($length) {	return array_map(function($key,$value) {$value[$key] = 1; return $value;}, range(0,$length-1),	array_fill(0, $length, array_fill(0,$length, 0)));}function print_identity($identity) { echo implode(PHP_EOL, array_map(function ($value) {return implode(' ', $value);},$identity));}print_identity(identity(10)); 
Output:
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


## PicoLisp

(de identity (Size)   (let L (need Size (1) 0)      (make         (do Size            (link (copy (rot L))) ) ) ) )

Test:

: (identity 3)-> ((1 0 0) (0 1 0) (0 0 1)) : (mapc println (identity 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)

## PL/I

 identity: procedure (A, n);   declare A(n,n) fixed controlled;   declare (i,n) fixed binary;   allocate A; A = 0;   do i = 1 to n; A(i,i) = 1; end;end identity; 

## PostScript

 % n  ident  [identity-matrix]% create an identity matrix of dimension n*n.% Uses a local dictionary for its one parameter, perhaps overkill.% Constructs arrays of arrays of integers using [], for loops, and stack manipulation./ident { 1 dict begin /n exch def    [    1 1 n {                              % [ i        [ exch                           % [ [ i        1 1 n {                          % [ [ i j            1 index eq { 1 }{ 0 } ifelse % [ [ i b            exch                         % [ [ b i        } for                            % [ [ b+ i        pop ]                            % [ [ b+ ]    } for                                % [ [b+]+ ]    ]end } def 

## PowerShell

 function identity($n) { 0..($n-1) | foreach{$row = @(0) *$n; $row[$_] = 1; ,$row}}function show($a) { $a | foreach{ "$_"} }$array = identity 4show$array 

Output:


1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

 $array[0][0]$array[0][1] 

Output:


1
0


## Prolog

Works with: SWi-Prolog
%rotates one list clockwise by one integerrotate(Int,List,Rotated) :-	integer(Int),	length(Suff,Int),	append(Pre,Suff,List),	append(Suff,Pre,Rotated).%rotates a list of lists by a list of integersrotate(LoInts,LoLists,Rotated) :-	is_list(LoInts),	maplist(rotate,LoInts,LoLists,Rotated). %helper functionappend_(Suff,Pre,List) :-	append([Pre],Suff,List).	idmatrix(N,IdMatrix):-	%make an N length list of 1s and append with N-1 0s	length(Ones,N),	maplist(=(1),Ones),	succ(N0,N),	length(Zeros,N0),	maplist(=(0),Zeros),	maplist(append_(Zeros),Ones,M),	%create the offsets at rotate each row	numlist(0,N0,Offsets),	rotate(Offsets,M,IdMatrix). main :-	idmatrix(5,I),	maplist(writeln,I). 
Output:
?- main.
[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]
true .


## PureBasic

>Procedure identityMatrix(Array i(2), size) ;valid only for size >= 0  ;formats array i() as an identity matrix of size x size  Dim i(size - 1, size - 1)   Protected j  For j = 0 To size - 1    i(j, j) = 1  Next EndProcedure  Procedure displayMatrix(Array a(2))  Protected rows = ArraySize(a(), 2), columns = ArraySize(a(), 1)  Protected i, j   For i = 0 To rows    For j = 0 To columns      Print(RSet(Str(a(i, j)), 3, " "))    Next    PrintN("")  NextEndProcedure If OpenConsole()  Dim i3(0, 0)  Dim i4(0, 0)   identityMatrix(i3(), 3)  identityMatrix(i4(), 4)   displayMatrix(i3())  PrintN("")  displayMatrix(i4())   Print(#CRLF$+ #CRLF$ + "Press ENTER to exit"): Input()  CloseConsole()EndIf
Output:
  1  0  0
0  1  0
0  0  1

1  0  0  0
0  1  0  0
0  0  1  0
0  0  0  1

## Python

### Nested lists

A simple solution, using nested lists to represent the matrix.

def identity(size):    matrix = [[0]*size for i in range(size)]    #matrix = [[0] * size] * size    #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists     for i in range(size):        matrix[i][i] = 1     for rows in matrix:        for elements in rows:            print elements,        print ""

### Nested maps and comprehensions

Works with: Python version 3.7
'''Identity matrices by maps and equivalent list comprehensions''' import operator  # idMatrix :: Int -> [[Int]]def idMatrix(n):    '''Identity matrix of order n,       expressed as a nested map.    '''    eq = curry(operator.eq)    xs = range(0, n)    return list(map(        lambda x: list(map(            compose(int)(eq(x)),            xs        )),        xs    ))  # idMatrix3 :: Int -> [[Int]]def idMatrix2(n):    '''Identity matrix of order n,       expressed as a nested comprehension.    '''    xs = range(0, n)    return ([int(x == y) for x in xs] for y in xs)  # TEST ----------------------------------------------------def main():    '''        Identity matrix of dimension five,        by two different routes.    '''    for f in [idMatrix, idMatrix2]:        print(            '\n' + f.__name__ + ':',            '\n\n' + '\n'.join(map(str, f(5))),        )  # GENERIC ------------------------------------------------- # compose (<<<) :: (b -> c) -> (a -> b) -> a -> cdef compose(g):    '''Right to left function composition.'''    return lambda f: lambda x: g(f(x))  # curry :: ((a, b) -> c) -> a -> b -> cdef curry(f):    '''A curried function derived       from an uncurried function.'''    return lambda a: lambda b: f(a, b)  # MAIN ---if __name__ == '__main__':    main()
Output:
idMatrix:

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

idMatrix2:

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

### Dict of points

A dict of tuples of two ints (x, y) are used to represent the matrix.

>>> def identity(size):...     return {(x, y):int(x == y) for x in range(size) for y in range(size)}... >>> size = 4>>> matrix = identity(size)>>> print('\n'.join(' '.join(str(matrix[(x, y)]) for x in range(size)) for y in range(size)))1 0 0 00 1 0 00 0 1 00 0 0 1>>> 

### Numpy

A solution using the numpy library

 np.mat(np.eye(size)) 

## Quackery

[ [] swap times    [ 0 i^ of 1 join 0 i of      join nested join ] ]  is identity ( n --> [ ) 5 identity echo
Output:
[ [ 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 ] ]


## R

When passed a single scalar argument, diag produces an identity matrix of size given by the scalar. For example:

diag(3)

produces:

     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

Or you can also use the method that is shown below

Identity_matrix=function(size){  x=matrix(0,size,size)  for (i in 1:size) {    x[i,i]=1  }  return(x)}

## Racket

 #lang racket(require math)(identity-matrix 5) 
Output:
(array #[#[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]])


## Raku

(formerly Perl 6)

Works with: rakudo version 2015-09-15
sub identity-matrix($n) { my @id; for flat ^$n X ^$n ->$i, $j { @id[$i][$j] = +($i == $j); } @id;} .say for identity-matrix(5); Output: [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] On the other hand, this may be clearer and/or faster: sub identity-matrix($n) {    my @id = [0 xx $n] xx$n;    @id[$_][$_] = 1 for ^$n; @id;} Here is yet an other way to do it: sub identity-matrix($n) {    [1, |(0 xx n-1)], *.rotate(-1) ... *[*-1]} ## Red Red[] identity-matrix: function [size][ matrix: copy [] repeat i size [ append/only matrix append/dup copy [] 0 size matrix/:i/:i: 1 ] matrix] probe identity-matrix 5 Output: [[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]]  ## REXX ### version 1 The REXX language doesn't have matrices as such, so the problem is largely how to display the "matrix". The code to display the matrices was kept as a stand-alone general-purpose (square) matrix display subroutine, which, in part, determines if the square matrix is indeed a square matrix based on the number of elements given. It also finds the maximum widths of the integer and decimal fraction parts (if any) and uses those widths to align (right-justify according to the [possibly implied] decimal point) the columns of the square matrix. It also tries to display a centered (and easier to read) matrix, along with a title. /*REXX program creates and displays any sized identity matrix (centered, with title).*/ do k=3 to 6 /* [↓] build and display a sq. matrix.*/ call ident_mat k /*build & display a KxK square matrix. */ end /*k*/ /* [↑] use general─purpose display sub*/exit /*stick a fork in it, we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/ident_mat: procedure; parse arg n;=              do    r=1  for n                   /*build identity matrix, by row and col*/                 do c=1  for n;     $=$ (r==c)  /*append  zero  or  one  (if on diag). */                 end   /*c*/              end      /*r*/           call showMat  'identity matrix of size'   n,   $return/*──────────────────────────────────────────────────────────────────────────────────────*/showMat: procedure; parse arg hdr,x; #=words(x) /*# is the number of matrix elements. */ dp= 0 /*DP: max width of decimal fractions. */ w= 0 /*W: max width of integer part. */ do n=1 until n*n>=#; _= word(x,n) /*determine the matrix order. */ parse var _ y '.' f; w= max(w, length(y)); dp= max(dp, length(f) ) end /*n*/ /* [↑] idiomatically find the widths. */ w= w +1 say; say center(hdr, max(length(hdr)+8, (w+1)*#%n), '─'); say #= 0 /*#: element #.*/ do row=1 for n; _= left('', n+w) /*indentation. */ do col=1 for n; #= # + 1 /*bump element.*/ _=_ right(format(word(x, #), , dp)/1, w) end /*col*/ /* [↑] division by unity normalizes #.*/ say _ /*display a single line of the matrix. */ end /*row*/ return output when using the default sizes (3 ──► 6) for generating four matrices: ────identity matrix of size 3──── 1 0 0 0 1 0 0 0 1 ────identity matrix of size 4──── 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ────identity matrix of size 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 ────identity matrix of size 6──── 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1  ### version 2 An alternative?!  /* REXX **************************************************************** show identity matrix of size n* I consider m.i.j to represent the matrix (not needed for showing)* 06.07.2012 Walter Pachl**********************************************************************/Parse Arg nSay 'Identity Matrix of size' n '(m.i.j IS the Matrix)'m.=0Do i=1 To n ol='' Do j=1 To n m.i.j=(i=j) ol=ol''format(m.i.j,2) /* or ol=ol (i=j) */ End Say ol End  Output: Identity Matrix of size 3 (m.i.j IS the Matrix) 1 0 0 0 1 0 0 0 1  This could be a 3-dimensional sparse matrix with one element set:  m.=0m.0=1000 /* the matrix' size */m.4.17.333='Walter'  ## Ring  size = 5im = newlist(size, size)identityMatrix(size, im)for r = 1 to size for c = 1 to size see im[r][c] next see nlnext func identityMatrix s, m m = newlist(s, s) for i = 1 to s m[i][i] = 1 next return m func newlist x, y if isstring(x) x=0+x ok if isstring(y) y=0+y ok alist = list(x) for t in alist t = list(y) next return alist  Output: 10000 01000 00100 00010 00001  Gui version  # Project : Identity Matrix# Date : 2022/16/02# Author : Gal Zsolt (~ CalmoSoft ~)# Email : <[email protected]> load "stdlib.ring"load "guilib.ring" size = 8C_Spacing = 1 C_ButtonBlueStyle = 'border-radius:6px;color:black; background-color: blue'C_ButtonOrangeStyle = 'border-radius:6px;color:black; background-color: orange' Button = newlist(size,size)LayoutButtonRow = list(size) app = new qApp { win = new qWidget() { setWindowTitle('Identity Matrix') move(500,100) reSize(600,600) winheight = win.height() fontSize = 18 + (winheight / 100) LayoutButtonMain = new QVBoxLayout() LayoutButtonMain.setSpacing(C_Spacing) LayoutButtonMain.setContentsmargins(0,0,0,0) for Row = 1 to size LayoutButtonRow[Row] = new QHBoxLayout() { setSpacing(C_Spacing) setContentsmargins(0,0,0,0) } for Col = 1 to size Button[Row][Col] = new QPushButton(win) { setSizePolicy(1,1) } LayoutButtonRow[Row].AddWidget(Button[Row][Col]) next LayoutButtonMain.AddLayout(LayoutButtonRow[Row]) next LayoutDataRow1 = new QHBoxLayout() { setSpacing(C_Spacing) setContentsMargins(0,0,0,0) } LayoutButtonMain.AddLayout(LayoutDataRow1) setLayout(LayoutButtonMain) show() } pBegin() exec() } func pBegin() for Row = 1 to size for Col = 1 to size if Row = Col Button[Row][Col].setStyleSheet(C_ButtonOrangeStyle) Button[Row][Col].settext("1") else Button[Row][Col].setStyleSheet(C_ButtonBlueStyle) Button[Row][Col].settext("0") ok next next score = 0  Output image: ## Ruby ### Using Array def identity(size) Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}end [4,5,6].each do |size| puts size, identity(size).map {|r| r.to_s}, ""end Output: 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] 6 [1, 0, 0, 0, 0, 0] [0, 1, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0] [0, 0, 0, 1, 0, 0] [0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 1]  ### Using Matrix  2.1.1 :001 > require "matrix" => true 2.1.1 :002 > Matrix.identity(5) => Matrix[[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]]  ## Run BASIC ' formats array im() of size imsfor ims = 4 to 6 print :print "--- Size: ";ims;" ---" Dim im(ims,ims) For i = 1 To ims im(i,i) = 1 next For row = 1 To ims print "["; cma$ = ""     For col = 1 To ims       print cma$;im(row, col); cma$ = ", "    next   print "]" nextnext ims
Output:
--- Size: 4 ---
[1, 0, 0, 0]
[0, 1, 0, 0]
[0, 0, 1, 0]
[0, 0, 0, 1]

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

--- Size: 6 ---
[1, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0]
[0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 1]

## Rust

Run with command-line containing the matrix size.

 extern crate num;struct Matrix<T> {    data: Vec<T>,    size: usize,} impl<T> Matrix<T>where    T: num::Num + Clone + Copy,{    fn new(size: usize) -> Self {        Self {            data: vec![T::zero(); size * size],            size: size,        }    }    fn get(&mut self, x: usize, y: usize) -> T {        self.data[x + self.size * y]    }    fn identity(&mut self) {        for (i, item) in self.data.iter_mut().enumerate() {            *item = if i % (self.size + 1) == 0 {                T::one()            } else {                T::zero()            }        }    }} fn main() {    let size = std::env::args().nth(1).unwrap().parse().unwrap();    let mut matrix = Matrix::<i32>::new(size);    matrix.identity();    for y in 0..size {        for x in 0..size {            print!("{} ", matrix.get(x, y));        }        println!();    }} 

## Scala

def identityMatrix(n:Int)=Array.tabulate(n,n)((x,y) => if(x==y) 1 else 0)def printMatrix[T](m:Array[Array[T]])=m map (_.mkString("[", ", ", "]")) mkString "\n" printMatrix(identityMatrix(5))
Output:
[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]

## Scheme

When representing a matrix as a collection of nested lists:

 (define (identity n)  (letrec      ((uvec 	(lambda (m i acc)	  (if (= i n)	      acc	      (uvec m (+ i 1)		    (cons (if (= i m) 1 0) acc)))))       (idgen	(lambda (i acc)	  (if (= i n)	      acc	      (idgen (+ i 1)		     (cons (uvec i 0 '()) acc))))))       (idgen 0 '()))) 

Test program:

 (display (identity 4)) 
Output:
((1 0 0 0) (0 1 0 0) (0 0 1 0) (0 0 0 1))


## Seed7

$include "seed7_05.s7i"; const type: matrix is array array integer; const func matrix: identity (in integer: size) is func result var matrix: identity is matrix.value; local var integer: index is 0; begin identity := size times size times 0; for index range 1 to size do identity[index][index] := 1; end for; end func; const proc: writeMat (in matrix: a) is func local var integer: i is 0; var integer: num is 0; begin for key i range a do for num range a[i] do write(num lpad 2); end for; writeln; end for; end func; const proc: main is func begin writeMat(identity(6)); end func; Output:  1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1  ## SenseTalk  set matrix to buildIdentityMatrix(3) repeat for each item in matrix put itend repeat set matrix to buildIdentityMatrix(17) repeat for each item in matrix put itend repeat function buildIdentityMatrix matrixSize set matrixList to () repeat matrixSize times set rowMatrixIndex to the counter set rowMatrix to () repeat matrixSize times if the counter equals rowMatrixIndex insert 1 after rowMatrix else insert 0 after rowMatrix end if end repeat insert rowMatrix nested after matrixList end repeat return matrixListend buildIdentityMatrix  Output for n 3 (1,0,0) (0,1,0) (0,0,1) Output for n 17 (1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) (0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) (0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0) (0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0) (0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0) (0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0) (0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0) (0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0) (0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0) (0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0) (0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0) (0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0) (0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0) (0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0) (0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0) (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0) (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1) ## Sidef func identity_matrix(n) { n.of { |i| n.of { |j| i == j ? 1 : 0 } }} for n (ARGV ? ARGV.map{.to_i} : [4, 5, 6]) { say "\n#{n}:" for row (identity_matrix(n)) { say row.join(' ') }} Output: 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 6: 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1  ## Sinclair ZX81 BASIC Works with 1k of RAM, but for a larger matrix you'll want at least 2k.  10 INPUT S 20 DIM M(S,S) 30 FOR I=1 TO S 40 LET M(I,I)=1 50 NEXT I 60 FOR I=1 TO S 70 SCROLL 80 FOR J=1 TO S 90 PRINT M(I,J);100 NEXT J110 PRINT120 NEXT I Input: 10 Output: 1000000000 0100000000 0010000000 0001000000 0000100000 0000010000 0000001000 0000000100 0000000010 0000000001 ## Smalltalk Works with: Pharo Smalltalk (Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString Output: '(1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 )'  ## Sparkling function unitMatrix(n) { return map(range(n), function(k1, v1) { return map(range(n), function(k2, v2) { return v2 == v1 ? 1 : 0; }); });} ## Standard ML  val eye= fn n => List.tabulate( n, fn i => List.tabulate( n, fn j=> if j=i then 1.0 else 0.0)); ## Stata ### Stata matrix . mat a = I(3). mat list a symmetric a[3,3] c1 c2 c3r1 1r2 0 1r3 0 0 1 ### Mata : I(3)[symmetric] 1 2 3 +-------------+ 1 | 1 | 2 | 0 1 | 3 | 0 0 1 | +-------------+ ## Swift Translation of: Elixir func identityMatrix(size: Int) -> [[Int]] { return (0..<size).map({i in return (0..<size).map({$0 == i ? 1 : 0})  })} print(identityMatrix(size: 5))
Output:
[[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]]

 templates identityMatrix  def n: $; [1..$n -> [1..~$-> 0, 1,$~..$n -> 0]] !end identityMatrix def identity: 5 -> identityMatrix;$identity... -> '|$(1);$(2..last)... -> ', $;';|' -> !OUT::write  Output: |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|  ## Tcl When representing a matrix as a collection of nested lists: proc I {rank {zero 0.0} {one 1.0}} { set m [lrepeat$rank [lrepeat $rank$zero]]    for {set i 0} {$i <$rank} {incr i} {	lset m $i$i $one } return$m}

Or alternatively with the help of the tcllib package for rectangular data structures:

Library: Tcllib (Package: struct::matrix)
package require struct::matrix proc I {rank {zero 0.0} {one 1.0}} {    set m [struct::matrix]    $m add columns$rank    $m add rows$rank    for {set i 0} {$i <$rank} {incr i} {	for {set j 0} {$j <$rank} {incr j} {	    $m set cell$i $j [expr {$i==$j ?$one : $zero}] } } return$m}

Demonstrating the latter: