Identity matrix: Difference between revisions

From Rosetta Code
Content added Content deleted
(Identity matrix in various BASIC dialents (BASIC256, QBasic and Yabasic))
imported>Arakov
 
(10 intermediate revisions by 9 users not shown)
Line 29: Line 29:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F identity_matrix(size)
<syntaxhighlight lang="11l">F identity_matrix(size)
V matrix = [[0] * size] * size
V matrix = [[0] * size] * size
L(i) 0 .< size
L(i) 0 .< size
Line 36: Line 36:


L(row) identity_matrix(3)
L(row) identity_matrix(3)
print(row)</lang>
print(row)</syntaxhighlight>


{{out}}
{{out}}
Line 46: Line 46:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Identity matrix 31/03/2017
<syntaxhighlight lang="360asm">* Identity matrix 31/03/2017
INDENMAT CSECT
INDENMAT CSECT
USING INDENMAT,R13 base register
USING INDENMAT,R13 base register
Line 118: Line 118:
A DS F a(n,n)
A DS F a(n,n)
YREGS
YREGS
END INDENMAT</lang>
END INDENMAT</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 134: Line 134:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC CreateIdentityMatrix(BYTE ARRAY mat,BYTE size)
<syntaxhighlight lang="action!">PROC CreateIdentityMatrix(BYTE ARRAY mat,BYTE size)
CARD pos
CARD pos
BYTE i,j
BYTE i,j
Line 191: Line 191:


LMARGIN=old ;restore left margin on the screen
LMARGIN=old ;restore left margin on the screen
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Identity_matrix.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Identity_matrix.png Screenshot from Atari 8-bit computer]
Line 213: Line 213:
=={{header|Ada}}==
=={{header|Ada}}==
When using floating point matrices in Ada 2005+ the function is defined as "Unit_Matrix" in Ada.Numerics.Generic_Real_Arrays. As a generic package it can work with user defined floating point types, or the predefined Short_Real_Arrays, Real_Arrays, and Long_Real_Arrays initializations. As seen below, the first indices of both dimensions can also be set since Ada array indices do not arbitrarily begin with a particular number.
When using floating point matrices in Ada 2005+ the function is defined as "Unit_Matrix" in Ada.Numerics.Generic_Real_Arrays. As a generic package it can work with user defined floating point types, or the predefined Short_Real_Arrays, Real_Arrays, and Long_Real_Arrays initializations. As seen below, the first indices of both dimensions can also be set since Ada array indices do not arbitrarily begin with a particular number.
<lang Ada>-- As prototyped in the Generic_Real_Arrays specification:
<syntaxhighlight lang="ada">-- As prototyped in the Generic_Real_Arrays specification:
-- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix;
-- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix;
-- For the task:
-- For the task:
mat : Real_Matrix := Unit_Matrix(5);</lang>
mat : Real_Matrix := Unit_Matrix(5);</syntaxhighlight>
For prior versions of Ada, or non floating point types its back to basics:
For prior versions of Ada, or non floating point types its back to basics:
<lang Ada>type Matrix is array(Positive Range <>, Positive Range <>) of Integer;
<syntaxhighlight lang="ada">type Matrix is array(Positive Range <>, Positive Range <>) of Integer;
mat : Matrix(1..5,1..5) := (others => (others => 0));
mat : Matrix(1..5,1..5) := (others => (others => 0));
-- then after the declarative section:
-- then after the declarative section:
for i in mat'Range(1) loop mat(i,i) := 1; end loop;</lang>
for i in mat'Range(1) loop mat(i,i) := 1; end loop;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 229: Line 229:
'''Note:''' The generic vector and matrix code should be moved to a more generic page.
'''Note:''' The generic vector and matrix code should be moved to a more generic page.


'''File: prelude/vector_base.a68'''<lang algol68>#!/usr/bin/a68g --script #
'''File: prelude/vector_base.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# -*- coding: utf-8 -*- #


Line 261: Line 261:
);
);


SKIP</lang>'''File: prelude/matrix_base.a68'''<lang algol68># -*- coding: utf-8 -*- #
SKIP</syntaxhighlight>'''File: prelude/matrix_base.a68'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #


# Define some generic matrix initialisation and printing operations #
# Define some generic matrix initialisation and printing operations #
Line 312: Line 312:
);
);


SKIP</lang>'''File: prelude/matrix_ident.a68'''<lang algol68># -*- coding: utf-8 -*- #
SKIP</syntaxhighlight>'''File: prelude/matrix_ident.a68'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #


PRIO IDENT = 9; # The same as I for COMPLex #
PRIO IDENT = 9; # The same as I for COMPLex #
Line 322: Line 322:
1 IDENT upb;
1 IDENT upb;


SKIP</lang>'''File: prelude/matrix.a68'''<lang algol68>#!/usr/bin/a68g --script #
SKIP</syntaxhighlight>'''File: prelude/matrix.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# -*- coding: utf-8 -*- #


Line 329: Line 329:
PR READ "prelude/matrix_ident.a68" PR;
PR READ "prelude/matrix_ident.a68" PR;


SKIP</lang>'''File: test/matrix_ident.a68'''<lang algol68>#!/usr/bin/a68g --script #
SKIP</syntaxhighlight>'''File: test/matrix_ident.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# -*- coding: utf-8 -*- #


Line 337: Line 337:
PR READ "prelude/matrix.a68" PR;
PR READ "prelude/matrix.a68" PR;


print(REPR IDENT 4)</lang>
print(REPR IDENT 4)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 347: Line 347:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% set m to an identity matrix of size s %
% set m to an identity matrix of size s %
procedure makeIdentity( real array m ( *, * )
procedure makeIdentity( real array m ( *, * )
Line 368: Line 368:
end text
end text


end.</lang>
end.</syntaxhighlight>

=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <jambo.h>

Main
Dim( 10,10 ) as eyes 'UMatrix'
Printnl ' "UNIT MATRIX:\n", UMatrix '
/* Classical method */
Dim (10,10) as zeros (ZM)
i=1
Iterator ( ++i, #(i<=10), #( ZM[i,i]=1 ) )
Printnl ' "UNIT MATRIX:\n", ZM '

/* unit matrix non square*/
Dim ( 5,8 ) as eyes 'rare unit matrix'
Printnl ' "RARE UNIT MATRIX:\n", rare unit matrix '
End
</syntaxhighlight>
{{out}}
<pre>
UNIT MATRIX:
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

UNIT MATRIX:
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

RARE UNIT MATRIX:
1,0,0,0,0,0,0,0
0,1,0,0,0,0,0,0
0,0,1,0,0,0,0,0
0,0,0,1,0,0,0,0
0,0,0,0,1,0,0,0

</pre>


=={{header|APL}}==
=={{header|APL}}==
Line 374: Line 431:


For a square matrix of 3:
For a square matrix of 3:
<lang apl>
<syntaxhighlight lang="apl">
∘.=⍨⍳3
∘.=⍨⍳3
1 0 0
1 0 0
0 1 0
0 1 0
0 0 1
0 0 1
</syntaxhighlight>
</lang>


For a function that makes an identity matrix:
For a function that makes an identity matrix:
<lang apl>
<syntaxhighlight lang="apl">
ID←{∘.=⍨⍳⍵}
ID←{∘.=⍨⍳⍵}
ID 5
ID 5
Line 390: Line 447:
0 0 0 1 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 1
</syntaxhighlight>
</lang>
An tacit function can be defined with one of the following equivalent lines:
An tacit function can be defined with one of the following equivalent lines:
<lang apl>
<syntaxhighlight lang="apl">
ID←∘.=⍨⍳
ID←∘.=⍨⍳
ID←⍳∘.=⍳
ID←⍳∘.=⍳
</syntaxhighlight>
</lang>


There is a more idomatic way however:
There is a more idomatic way however:
<lang apl>
<syntaxhighlight lang="apl">
ID←{⍵ ⍵ ρ 1, ⍵ρ0}
ID←{⍵ ⍵ ρ 1, ⍵ρ0}
</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang AppleScript>--------------------- IDENTITY MATRIX ----------------------
<syntaxhighlight lang="applescript">--------------------- IDENTITY MATRIX ----------------------


-- identityMatrix :: Int -> [(0|1)]
-- identityMatrix :: Int -> [(0|1)]
Line 511: Line 568:
set my text item delimiters to dlm
set my text item delimiters to dlm
s
s
end unlines</lang>
end unlines</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[1, 0, 0, 0, 0]
<pre>[1, 0, 0, 0, 0]
Line 520: Line 577:
----
----
===Simple alternative===
===Simple alternative===
<lang applescript>on indentityMatrix(n)
<syntaxhighlight lang="applescript">on indentityMatrix(n)
set digits to {}
set digits to {}
set m to n - 1
set m to n - 1
Line 536: Line 593:
end indentityMatrix
end indentityMatrix


return indentityMatrix(5)</lang>
return indentityMatrix(5)</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{{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}}</lang>
<syntaxhighlight lang="applescript">{{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}}</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>identityM: function [n][
<syntaxhighlight lang="rebol">identityM: function [n][
result: array.of: @[n n] 0
result: array.of: @[n n] 0
loop 0..dec n 'i -> result\[i]\[i]: 1
loop 0..dec n 'i -> result\[i]\[i]: 1
Line 553: Line 610:
loop identityM sz => print
loop identityM sz => print
print ""
print ""
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 580: Line 637:
=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoft basic">
<lang Applesoft BASIC>
100 INPUT "MATRIX SIZE:"; SIZE%
100 INPUT "MATRIX SIZE:"; SIZE%
110 GOSUB 200"IDENTITYMATRIX
110 GOSUB 200"IDENTITYMATRIX
Line 596: Line 653:
240 LET IM(I, I) = 1 : NEXT I
240 LET IM(I, I) = 1 : NEXT I
250 RETURN :IM
250 RETURN :IM
</syntaxhighlight>
</lang>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
{{trans|Applesoft BASIC}}
{{trans|Applesoft BASIC}}
{{works with|Commodore BASIC|2.0}}
{{works with|Commodore BASIC|2.0}}
<lang GWBASIC>100 INPUT "MATRIX SIZE:"; SIZE
<syntaxhighlight lang="gwbasic">100 INPUT "MATRIX SIZE:"; SIZE
110 GOSUB 200: REM IDENTITYMATRIX
110 GOSUB 200: REM IDENTITYMATRIX
120 FOR R = 0 TO SIZE
120 FOR R = 0 TO SIZE
Line 617: Line 674:
240 IM(I, I) = 1
240 IM(I, I) = 1
250 NEXT I
250 NEXT I
260 RETURN</lang>
260 RETURN</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
Line 623: Line 680:
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
{{trans|IS-BASIC}}
{{trans|IS-BASIC}}
<lang qbasic>SUB inicio(identity())
<syntaxhighlight lang="qbasic">SUB inicio(identity())
FOR i = LBOUND(identity,1) TO UBOUND(identity,1)
FOR i = LBOUND(identity,1) TO UBOUND(identity,1)
FOR j = LBOUND(identity,2) TO UBOUND(identity,2)
FOR j = LBOUND(identity,2) TO UBOUND(identity,2)
Line 648: Line 705:


CALL inicio(identity())
CALL inicio(identity())
CALL mostrar(identity())</lang>
CALL mostrar(identity())</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang BASIC256>arraybase 1
<syntaxhighlight lang="basic256">arraybase 1
do
do
input "Enter size of matrix: ", n
input "Enter size of matrix: ", n
Line 676: Line 733:
else
else
print "Matrix is too big to display on 80 column console"
print "Matrix is too big to display on 80 column console"
end if</lang>
end if</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>

==={{header|XBasic}}===
{{works with|Windows XBasic}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">PROGRAM "Identity matrix"
VERSION "0.0000"

DECLARE FUNCTION Entry ()

FUNCTION Entry ()
DO
n = SBYTE(INLINE$("Enter size of matrix: "))
LOOP UNTIL n > 0

DIM identity[n, n] '' all zero by default

' enter 1s in diagonal elements
FOR i = 1 TO n
identity[i, i] = 1
NEXT 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 i
ELSE
PRINT "Matrix is too big to display on 80 column console"
END IF

END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
{{out}}
<pre>Same as FreeBASIC entry.</pre>
<pre>Same as FreeBASIC entry.</pre>
Line 682: Line 778:
==={{header|Yabasic}}===
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<lang freebasic>repeat
<syntaxhighlight lang="freebasic">repeat
input "Enter size of matrix: " n
input "Enter size of matrix: " n
until n > 0
until n > 0
Line 705: Line 801:
else
else
print "Matrix is too big to display on 80 column console"
print "Matrix is too big to display on 80 column console"
end if</lang>
end if</syntaxhighlight>
{{out}}
{{out}}
<pre>Same as FreeBASIC entry.</pre>
<pre>Same as FreeBASIC entry.</pre>


=={{header|ATS}}==
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
(* ****** ****** *)
//
//
Line 744: Line 840:
//
//
} (* end of [main0] *)
} (* end of [main0] *)
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>msgbox % Clipboard := I(6)
<syntaxhighlight lang="autohotkey">msgbox % Clipboard := I(6)
return
return


Line 762: Line 858:
s .= " "
s .= " "
return Rtrim(r,"`n") "`n" s "--"
return Rtrim(r,"`n") "`n" s "--"
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 777: Line 873:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f IDENTITY_MATRIX.AWK size
# syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
BEGIN {
Line 795: Line 891:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5
<pre>
<pre>
Line 806: Line 902:


=={{header|Bash}}==
=={{header|Bash}}==
<syntaxhighlight lang="bash">
<lang Bash>
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
</syntaxhighlight>
</lang>
{{out}} for command: ./scriptname 5
{{out}} for command: ./scriptname 5
<pre>
<pre>
Line 820: Line 916:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INPUT "Enter size of matrix: " size%
<syntaxhighlight lang="bbcbasic"> INPUT "Enter size of matrix: " size%
PROCidentitymatrix(size%, im())
PROCidentitymatrix(size%, im())
FOR r% = 0 TO size%-1
FOR r% = 0 TO size%-1
Line 836: Line 932:
m(i%,i%) = 1
m(i%,i%) = 1
NEXT
NEXT
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|Beads}}==
=={{header|Beads}}==
<lang beads>beads 1 program 'Identity matrix'
<syntaxhighlight lang="beads">beads 1 program 'Identity matrix'


var
var
Line 848: Line 944:
loop from:1 to:n index:i
loop from:1 to:n index:i
loop from:1 to:n index:j
loop from:1 to:n index:j
id[i,j] = 1 if i == j else 0</lang>
id[i,j] = 1 if i == j else 0</syntaxhighlight>


{{out}}
{{out}}
Line 863: Line 959:
Neither very elegant nor short but it'll do
Neither very elegant nor short but it'll do


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp
blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp
1 0 0 0 0 0
1 0 0 0 0 0
Line 871: Line 967:
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 0 1
0 0 0 0 0 1
</syntaxhighlight>
</lang>


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


<lang burlesque>
<syntaxhighlight lang="burlesque">
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e!
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e!
</syntaxhighlight>
</lang>


Shorter alternative:
Shorter alternative:


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 6 ^^^^10\/**XXcy\/co.+sp
blsq ) 6 ^^^^10\/**XXcy\/co.+sp
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{header|BQN}}==
<lang>⍝ Using table
<syntaxhighlight lang="text">⍝ Using table
Eye ← =⌜˜∘↕
Eye ← =⌜˜∘↕
•Show Eye 3
•Show Eye 3
Line 892: Line 988:
⍝ Using reshape
⍝ Using reshape
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0}
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0}
Eye1 5</lang>
Eye1 5</syntaxhighlight>
<lang>┌─
<syntaxhighlight lang="text">┌─
╵ 1 0 0
╵ 1 0 0
0 1 0
0 1 0
Line 905: Line 1,001:
0 0 0 0 1
0 0 0 0 1
</syntaxhighlight>
</lang>


<code>Eye</code> generates an identity matrix using a table of equality for [0,n).
<code>Eye</code> generates an identity matrix using a table of equality for [0,n).
Line 914: Line 1,010:


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
Line 953: Line 1,049:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Linq;
using System.Linq;
Line 992: Line 1,088:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,005: Line 1,101:
=={{header|C++}}==
=={{header|C++}}==
{{libheader|STL}}
{{libheader|STL}}
<lang cpp>template<class T>
<syntaxhighlight lang="cpp">template<class T>
class matrix
class matrix
{
{
Line 1,052: Line 1,148:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{libheader|boost}}
{{libheader|boost}}
<lang cpp>
<syntaxhighlight lang="cpp">
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix.hpp>


Line 1,078: Line 1,174:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,090: Line 1,186:


=={{header|Clio}}==
=={{header|Clio}}==
<lang clio>fn identity-matrix n:
<syntaxhighlight lang="clio">fn identity-matrix n:
[0:n] -> * fn i:
[0:n] -> * fn i:
[0:n] -> * if = i: 1
[0:n] -> * if = i: 1
else: 0
else: 0


5 -> identity-matrix -> * print</lang>
5 -> identity-matrix -> * print</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 1,101: Line 1,197:


The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g.
The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g.
<lang clojure> '( (0 1) (2 3) )
<syntaxhighlight lang="clojure"> '( (0 1) (2 3) )
</syntaxhighlight>
</lang>
, then care to remove the vec function.
, then care to remove the vec function.
<lang clojure>(defn identity-matrix [n]
<syntaxhighlight lang="clojure">(defn identity-matrix [n]
(let [row (conj (repeat (dec n) 0) 1)]
(let [row (conj (repeat (dec n) 0) 1)]
(vec
(vec
Line 1,110: Line 1,206:
(vec
(vec
(reduce conj (drop i row ) (take i row)))))))
(reduce conj (drop i row ) (take i row)))))))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang clojure>=> (identity-matrix 5)
<syntaxhighlight lang="clojure">=> (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]]
[[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]]
</syntaxhighlight>
</lang>


The following is a more idomatic definition that utilizes infinite lists and cycling.
The following is a more idomatic definition that utilizes infinite lists and cycling.
<lang clojure>
<syntaxhighlight lang="clojure">
(defn identity-matrix [n]
(defn identity-matrix [n]
(take n
(take n
(partition n (dec n)
(partition n (dec n)
(cycle (conj (repeat (dec n) 0) 1)))))
(cycle (conj (repeat (dec n) 0) 1)))))
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 1,128: Line 1,224:
Common Lisp provides multi-dimensional arrays.
Common Lisp provides multi-dimensional arrays.


<lang lisp>(defun make-identity-matrix (n)
<syntaxhighlight lang="lisp">(defun make-identity-matrix (n)
(let ((array (make-array (list n n) :initial-element 0)))
(let ((array (make-array (list n n) :initial-element 0)))
(loop for i below n do (setf (aref array i i) 1))
(loop for i below n do (setf (aref array i i) 1))
array))
array))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,138: Line 1,234:
#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))
#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))


<lang lisp>(defun identity-matrix (n)
<syntaxhighlight lang="lisp">(defun identity-matrix (n)
(loop for a from 1 to n
(loop for a from 1 to n
collect (loop for e from 1 to n
collect (loop for e from 1 to n
if (= a e) collect 1
if (= a e) collect 1
else collect 0)))
else collect 0)))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,153: Line 1,249:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Algebras;
MODULE Algebras;
IMPORT StdLog,Strings;
IMPORT StdLog,Strings;
Line 1,189: Line 1,285:
END Do;
END Do;
END Algebras.
END Algebras.
</syntaxhighlight>
</lang>
Execute: ^Q Algebras.Do<br/>
Execute: ^Q Algebras.Do<br/>
{{out}}
{{out}}
Line 1,201: Line 1,297:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.traits;
<syntaxhighlight lang="d">import std.traits;


T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
Line 1,230: Line 1,326:


// auto id3 = matId!(const int)(2); // cant't compile
// auto id3 = matId!(const int)(2); // cant't compile
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[[1, 0, 0, 0, 0],
<pre>[[1, 0, 0, 0, 0],
Line 1,243: Line 1,339:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program IdentityMatrix;
<syntaxhighlight lang="delphi">program IdentityMatrix;


// Modified from the Pascal version
// Modified from the Pascal version
Line 1,267: Line 1,363:
writeln;
writeln;
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,277: Line 1,373:
0 0 0 0 1
0 0 0 0 1
</pre>
</pre>

=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
proc idmat lng . mat[][] .
len mat[][] lng
for i to lng
len mat[i][] lng
mat[i][i] = 1
.
.
idmat 4 m[][]
print m[][]
</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,341: Line 1,450:


end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,358: Line 1,467:


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 6.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
import system'collections;
import system'collections;
Line 1,365: Line 1,474:
public program()
public program()
{
{
var n := console.write:"Enter the matrix size:".readLine().toInt();
var n := console.write("Enter the matrix size:").readLine().toInt();
var identity := new Range(0, n).selectBy:(i => new Range(0,n).selectBy:(j => (i == j).iif(1,0) ).summarize(new ArrayList()))
var identity := new Range(0, n).selectBy::(i => new Range(0,n).selectBy::(j => (i == j).iif(1,0) ).summarize(new ArrayList()))
.summarize(new ArrayList());
.summarize(new ArrayList());
identity.forEach:
identity.forEach::
(row) { console.printLine(row.asEnumerable()) }
(row) { console.printLine(row.asEnumerable()) }
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,382: Line 1,491:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Matrix do
<syntaxhighlight lang="elixir">defmodule Matrix do
def identity(n) do
def identity(n) do
Enum.map(0..n-1, fn i ->
Enum.map(0..n-1, fn i ->
Line 1,390: Line 1,499:
end
end


IO.inspect Matrix.identity(5)</lang>
IO.inspect Matrix.identity(5)</syntaxhighlight>


{{out}}
{{out}}
Line 1,399: Line 1,508:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>%% Identity Matrix in Erlang for the Rosetta Code Wiki.
<syntaxhighlight lang="erlang">%% Identity Matrix in Erlang for the Rosetta Code Wiki.
%% Implemented by Arjun Sunel
%% Implemented by Arjun Sunel


Line 1,409: Line 1,518:


identity(Size) ->
identity(Size) ->
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</lang>
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM IDENTITY
PROGRAM IDENTITY


Line 1,433: Line 1,542:
END FOR
END FOR
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>


=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
function IdentityMatrix(n)
function IdentityMatrix(n)
$ X:=zeros(n,n);
$ X:=zeros(n,n);
Line 1,445: Line 1,554:
$ return X;
$ return X;
$endfunction
$endfunction
</syntaxhighlight>
</lang>


<syntaxhighlight lang="euler math toobox">
<lang Euler Math Toobox>
>function IdentityMatrix (n:index)
>function IdentityMatrix (n:index)
$ return setdiag(zeros(n,n),0,1);
$ return setdiag(zeros(n,n),0,1);
$endfunction
$endfunction
</syntaxhighlight>
</lang>


<lang>
<syntaxhighlight lang="text">
>id(5)
>id(5)
</syntaxhighlight>
</lang>


=={{header|Excel}}==
=={{header|Excel}}==
Line 1,467: Line 1,576:


{{Works with|Office 365 betas 2021}}
{{Works with|Office 365 betas 2021}}
<lang lisp>IDMATRIX
<syntaxhighlight lang="lisp">IDMATRIX
=LAMBDA(n,
=LAMBDA(n,
LET(
LET(
Line 1,479: Line 1,588:
)
)
)
)
)</lang>
)</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,577: Line 1,686:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
Builds a 2D matrix with the given square size.
Builds a 2D matrix with the given square size.
<syntaxhighlight lang="fsharp">
<lang FSharp>
let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0)
let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
<syntaxhighlight lang="fsharp">
<lang FSharp>
ident 10;;
ident 10;;
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]
Line 1,594: Line 1,703:
[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; 0; 1]]
[0; 0; 0; 0; 0; 0; 0; 0; 0; 1]]
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
{{works with|Factor|0.99 2020-07-03}}
<lang factor>USING: math.matrices prettyprint ;
<syntaxhighlight lang="factor">USING: math.matrices prettyprint ;


6 <identity-matrix> .</lang>
6 <identity-matrix> .</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,652: Line 1,761:


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>
<syntaxhighlight lang="fermat">
Func Identity(n)=Array id[n,n];[id]:=[1].
Func Identity(n)=Array id[n,n];[id]:=[1].


Identity(7)
Identity(7)
[id]
[id]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,671: Line 1,780:
{{libheader|Forth Scientific Library}}
{{libheader|Forth Scientific Library}}
{{works with|gforth|0.7.9_20170308}}
{{works with|gforth|0.7.9_20170308}}
<lang forth>S" fsl-util.fs" REQUIRED
<syntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED


: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix
: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix
Line 1,686: Line 1,795:
6 6 float matrix a{{
6 6 float matrix a{{
a{{ 6 build-identity
a{{ 6 build-identity
6 6 a{{ }}fprint</lang>
6 6 a{{ }}fprint</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|95}}
{{works with|Fortran|95}}


<lang fortran>
<syntaxhighlight lang="fortran">
program identitymatrix
program identitymatrix


Line 1,715: Line 1,824:


end program identitymatrix
end program identitymatrix
</syntaxhighlight>
</lang>


===Notorious trick===
===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.
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.
<lang Fortran> Program Identity
<syntaxhighlight lang="fortran"> Program Identity
Integer N
Integer N
Parameter (N = 666)
Parameter (N = 666)
Line 1,727: Line 1,836:
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i)
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i)
END</lang>
END</syntaxhighlight>


The <code>ForAll</code> 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:
The <code>ForAll</code> 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:
<lang Fortran> DO 1 I = 1,N
<syntaxhighlight lang="fortran"> DO 1 I = 1,N
DO 1 J = 1,N
DO 1 J = 1,N
1 A(I,J) = (I/J)*(J/I)</lang>
1 A(I,J) = (I/J)*(J/I)</syntaxhighlight>
Array assignment statements are also a feature of F90 and later.
Array assignment statements are also a feature of F90 and later.


Line 1,738: Line 1,847:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim As Integer n
Dim As Integer n
Line 1,769: Line 1,878:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>
Sample input/output
Sample input/output
{{out}}
{{out}}
Line 1,785: Line 1,894:
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.
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.


<lang frink>n = parseInt[input["Enter matrix dimension as an integer: "]]
<syntaxhighlight lang="frink">n = parseInt[input["Enter matrix dimension as an integer: "]]
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</lang>
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</syntaxhighlight>


{{out}}
{{out}}
Line 1,801: Line 1,910:


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 )
<syntaxhighlight lang="funl">def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 )


println( identity(3) )</lang>
println( identity(3) )</syntaxhighlight>


{{out}}
{{out}}
Line 1,813: Line 1,922:
=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Identity_matrix}}
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 &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.


'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org 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.

[[File:Fōrmulæ - Identity matrix 01.png]]

'''Test cases'''

[[File:Fōrmulæ - Identity matrix 02.png]]

[[File:Fōrmulæ - Identity matrix 03.png]]

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"

local fn IdentityMatrix( n as NSInteger ) as CFStringRef
NSInteger i, j
CFMutableArrayRef tempArr = fn MutableArrayWithCapacity( n )
CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )

for i = 0 to n - 1
MutableArrayRemoveAllObjects( tempArr )
for j = 0 to n - 1
MutableArrayInsertObjectAtIndex( tempArr, @"0", j )
next
MutableArrayReplaceObjectAtIndex( tempArr, @"1", i )
MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) )
MutableStringAppendString( mutStr, @"\n" )
next
end 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
</syntaxhighlight>
{{output}}
<pre>
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
</pre>


In '''[https://formulae.org/?example=Identity_matrix this]''' page you can see the program(s) related to this task and their results.


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Built-in
<syntaxhighlight lang="gap"># Built-in
IdentityMat(3);
IdentityMat(3);


# One can also specify the base ring
# One can also specify the base ring
IdentityMat(3, Integers mod 10);</lang>
IdentityMat(3, Integers mod 10);</syntaxhighlight>




=={{header|Go}}==
=={{header|Go}}==
===Library gonum/mat===
===Library gonum/mat===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,846: Line 2,026:
func main() {
func main() {
fmt.Println(mat.Formatted(eye(3)))
fmt.Println(mat.Formatted(eye(3)))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,856: Line 2,036:
===Library go.matrix===
===Library go.matrix===
A somewhat earlier matrix library for Go.
A somewhat earlier matrix library for Go.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,866: Line 2,046:
func main() {
func main() {
fmt.Println(mat.Eye(3))
fmt.Println(mat.Eye(3))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,876: Line 2,056:
===From scratch===
===From scratch===
'''Simplest: ''' A matrix as a slice of slices, allocated separately.
'''Simplest: ''' A matrix as a slice of slices, allocated separately.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,892: Line 2,072:
}
}
return m
return m
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
No special formatting method used.
No special formatting method used.
Line 1,900: Line 2,080:


'''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.
'''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.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,917: Line 2,097:
}
}
return m
return m
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,923: Line 2,103:


'''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.
'''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.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,956: Line 2,136:
}
}
return m
return m
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,967: Line 2,147:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def makeIdentityMatrix = { n ->
<syntaxhighlight lang="groovy">def makeIdentityMatrix = { n ->
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>(2..6).each { order ->
<syntaxhighlight lang="groovy">(2..6).each { order ->
def iMatrix = makeIdentityMatrix(order)
def iMatrix = makeIdentityMatrix(order)
iMatrix.each { println it }
iMatrix.each { println it }
println()
println()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,005: Line 2,185:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]</lang>
<syntaxhighlight lang="haskell">matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]</syntaxhighlight>
And a function to show matrix pretty:
And a function to show matrix pretty:
<lang haskell>showMat :: [[Int]] -> String
<syntaxhighlight lang="haskell">showMat :: [[Int]] -> String
showMat = unlines . map (unwords . map show)</lang>
showMat = unlines . map (unwords . map show)</syntaxhighlight>




<lang haskell>*Main> putStr $ showMat $ matId 9
<syntaxhighlight lang="haskell">*Main> putStr $ showMat $ matId 9
1 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 1 0 0 0 0 0 0 0
Line 2,021: Line 2,201:
0 0 0 0 0 0 0 1 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 1
</syntaxhighlight>
</lang>


We could alternatively bypassing the syntactic sugaring of list comprehension notation, and use a bind function directly:
We could alternatively bypassing the syntactic sugaring of list comprehension notation, and use a bind function directly:


<lang haskell>idMatrix :: Int -> [[Int]]
<syntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]]
idMatrix n =
idMatrix n =
let xs = [1 .. n]
let xs = [1 .. n]
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</lang>
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</syntaxhighlight>


or reduce the number of terms a little to:
or reduce the number of terms a little to:
<lang haskell>idMatrix :: Int -> [[Int]]
<syntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]]
idMatrix n =
idMatrix n =
let xs = [1 .. n]
let xs = [1 .. n]
Line 2,037: Line 2,217:


main :: IO ()
main :: IO ()
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</lang>
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</syntaxhighlight>
{{Out}}
{{Out}}
<pre>1 0 0 0 0
<pre>1 0 0 0 0
Line 2,048: Line 2,228:


This code works for Icon and Unicon.
This code works for Icon and Unicon.
<lang unicon>link matrix
<syntaxhighlight lang="unicon">link matrix
procedure main(argv)
procedure main(argv)
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.")
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.")
Line 2,054: Line 2,234:
write_matrix(&output,matrix1)
write_matrix(&output,matrix1)
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,069: Line 2,249:


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "Identity.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "Identity.bas"
110 INPUT PROMPT "Enter size of matrix: ":N
110 INPUT PROMPT "Enter size of matrix: ":N
120 NUMERIC A(1 TO N,1 TO N)
120 NUMERIC A(1 TO N,1 TO N)
Line 2,089: Line 2,269:
280 PRINT
280 PRINT
290 NEXT
290 NEXT
300 END DEF</lang>
300 END DEF</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j> = i. 4 NB. create an Identity matrix of size 4
<syntaxhighlight lang="j"> = i. 4 NB. create an Identity matrix of size 4
1 0 0 0
1 0 0 0
0 1 0 0
0 1 0 0
Line 2,103: Line 2,283:
0 0 1 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 1 0
0 0 0 0 1</lang>
0 0 0 0 1</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang Java>public class PrintIdentityMatrix {
<syntaxhighlight lang="java">public class PrintIdentityMatrix {


public static void main(String[] args) {
public static void main(String[] args) {
Line 2,118: Line 2,298:
.forEach(System.out::println);
.forEach(System.out::println);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,131: Line 2,311:
===ES5===
===ES5===


<lang Javascript>function idMatrix(n) {
<syntaxhighlight lang="javascript">function idMatrix(n) {
return Array.apply(null, new Array(n))
return Array.apply(null, new Array(n))
.map(function (x, i, xs) {
.map(function (x, i, xs) {
Line 2,138: Line 2,318:
})
})
});
});
}</lang>
}</syntaxhighlight>


===ES6===
===ES6===
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {


// identityMatrix :: Int -> [[Int]]
// identityMatrix :: Int -> [[Int]]
Line 2,156: Line 2,336:
.map(JSON.stringify)
.map(JSON.stringify)
.join('\n');
.join('\n');
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[1,0,0,0,0]
<pre>[1,0,0,0,0]
Line 2,166: Line 2,346:
=={{header|jq}}==
=={{header|jq}}==
===Construction===
===Construction===
<lang jq>def identity(n):
<syntaxhighlight lang="jq">def identity(n):
[range(0;n) | 0] as $row
[range(0;n) | 0] as $row
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</lang>
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</syntaxhighlight>
Example:
Example:
<lang jq>identity(4)</lang>produces:
<syntaxhighlight lang="jq">identity(4)</syntaxhighlight>produces:
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]


===Using matrix/2===
===Using matrix/2===
Using the definition of matrix/2 at [[Create_a_two-dimensional_array_at_runtime#jq]]:
Using the definition of matrix/2 at [[Create_a_two-dimensional_array_at_runtime#jq]]:
<lang jq>def identity(n):
<syntaxhighlight lang="jq">def identity(n):
reduce range(0;n) as $i
reduce range(0;n) as $i
(0 | matrix(n;n); .[$i][$i] = 1);
(0 | matrix(n;n); .[$i][$i] = 1);
</syntaxhighlight>
</lang>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Identity matrix, in Jsish */
<syntaxhighlight lang="javascript">/* Identity matrix, in Jsish */
function identityMatrix(n) {
function identityMatrix(n) {
var mat = new Array(n).fill(0);
var mat = new Array(n).fill(0);
Line 2,213: Line 2,393:
[ 0, 0, 0, 1 ]
[ 0, 0, 0, 1 ]
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 2,223: Line 2,403:
representing an identity matrix of any size,
representing an identity matrix of any size,
boolean by default, that can be multiplied by a scalar
boolean by default, that can be multiplied by a scalar
<lang Julia>using LinearAlgebra
<syntaxhighlight lang="julia">using LinearAlgebra
unitfloat64matrix = 1.0I</lang>
unitfloat64matrix = 1.0I</syntaxhighlight>


UniformScaling object can be used as a function to construct a Diagonal
UniformScaling object can be used as a function to construct a Diagonal
matrix of given size, that can be converted to a full matrix using <tt>collect</tt>
matrix of given size, that can be converted to a full matrix using <tt>collect</tt>
<lang Julia>using LinearAlgebra
<syntaxhighlight lang="julia">using LinearAlgebra
diagI3 = 1.0I(3)
diagI3 = 1.0I(3)
fullI3 = collect(diagI3)</lang>
fullI3 = collect(diagI3)</syntaxhighlight>


The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are
The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are


<lang Julia>using LinearAlgebra
<syntaxhighlight lang="julia">using LinearAlgebra
fullI3 = Matrix{Float64}(I, 3, 3)
fullI3 = Matrix{Float64}(I, 3, 3)
fullI3 = Array{Float64}(I, 3, 3)
fullI3 = Array{Float64}(I, 3, 3)
fullI3 = Array{Float64,2}(I, 3, 3)
fullI3 = Array{Float64,2}(I, 3, 3)
fullI3 = zeros(3,3) + I</lang>
fullI3 = zeros(3,3) + I</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==


<lang K> =4
<syntaxhighlight lang="k"> =4
(1 0 0 0
(1 0 0 0
0 1 0 0
0 1 0 0
Line 2,253: Line 2,433:
0 0 0 1 0
0 0 0 1 0
0 0 0 0 1)
0 0 0 0 1)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 2,272: Line 2,452:
else
else
println("Matrix is too big to display on 80 column console")
println("Matrix is too big to display on 80 column console")
}</lang>
}</syntaxhighlight>
Sample input/output
Sample input/output
{{out}}
{{out}}
Line 2,286: Line 2,466:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def identity
{def identity
{lambda {:n}
{lambda {:n}
Line 2,301: Line 2,481:
{identity 5}
{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]]
-> [[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]]
</syntaxhighlight>
</lang>




=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: identity-matrix
<syntaxhighlight lang="lang5">: identity-matrix
dup iota 'A set
dup iota 'A set


Line 2,312: Line 2,492:
;
;


5 identity-matrix .</lang>
5 identity-matrix .</syntaxhighlight>
{{out}}
{{out}}
<pre>[
<pre>[
Line 2,324: Line 2,504:
=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>
<syntaxhighlight lang="lisp">
(defun identity
(defun identity
((`(,m ,n))
((`(,m ,n))
Line 2,333: Line 2,513:
(defun identity (m n)
(defun identity (m n)
(lists:duplicate m (lists:duplicate n 1)))
(lists:duplicate m (lists:duplicate n 1)))
</syntaxhighlight>
</lang>


From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix:
From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix:


<lang lisp>
<syntaxhighlight lang="lisp">
> (identity 3)
> (identity 3)
((1 1 1) (1 1 1) (1 1 1))
((1 1 1) (1 1 1) (1 1 1))
Line 2,345: Line 2,525:
((1 1 1) (1 1 1) (1 1 1))
((1 1 1) (1 1 1) (1 1 1))


</syntaxhighlight>
</lang>


=={{header|LSL}}==
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
To test it yourself; rez a box on the ground, and add the following as a New Script.
<lang LSL>default {
<syntaxhighlight lang="lsl">default {
state_entry() {
state_entry() {
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
Line 2,367: Line 2,547:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>You: 0
<pre>You: 0
Line 2,388: Line 2,568:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
function identity_matrix (size)
function identity_matrix (size)
local m = {}
local m = {}
Line 2,406: Line 2,586:
end
end


print_matrix(identity_matrix(5))</lang>
print_matrix(identity_matrix(5))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,417: Line 2,597:
=={{header|Maple}}==
=={{header|Maple}}==
One of a number of ways to do this:
One of a number of ways to do this:
<syntaxhighlight lang="maple">
<lang Maple>
> LinearAlgebra:-IdentityMatrix( 4 );
> LinearAlgebra:-IdentityMatrix( 4 );
[1 0 0 0]
[1 0 0 0]
Line 2,426: Line 2,606:
[ ]
[ ]
[0 0 0 1]
[0 0 0 1]
</syntaxhighlight>
</lang>
Here, for instance, is another, in which the entries are (4-byte) floats.
Here, for instance, is another, in which the entries are (4-byte) floats.
<syntaxhighlight lang="maple">
<lang Maple>
> Matrix( 4, shape = scalar[1], datatype = float[4] );
> Matrix( 4, shape = scalar[1], datatype = float[4] );
[1. 0. 0. 0.]
[1. 0. 0. 0.]
Line 2,437: Line 2,617:
[ ]
[ ]
[0. 0. 0. 1.]
[0. 0. 0. 1.]
</syntaxhighlight>
</lang>
Yet another, with 2-byte integer entries:
Yet another, with 2-byte integer entries:
<syntaxhighlight lang="maple">
<lang Maple>
> Matrix( 4, shape = identity, datatype = integer[ 2 ] );
> Matrix( 4, shape = identity, datatype = integer[ 2 ] );
[1 0 0 0]
[1 0 0 0]
Line 2,448: Line 2,628:
[ ]
[ ]
[0 0 0 1]
[0 0 0 1]
</syntaxhighlight>
</lang>


=={{header|MathCortex}}==
=={{header|MathCortex}}==
<lang MathCortex>I = eye(10)</lang>
<syntaxhighlight lang="mathcortex">I = eye(10)</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>IdentityMatrix[4]</lang>
<syntaxhighlight lang="mathematica">IdentityMatrix[4]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
The '''eye''' function create the identity (I) matrix, e.g.:
The '''eye''' function create the identity (I) matrix, e.g.:


<lang MATLAB>I = eye(10)</lang>
<syntaxhighlight lang="matlab">I = eye(10)</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>ident(4);
<syntaxhighlight lang="maxima">ident(4);
/* matrix([1, 0, 0, 0],
/* matrix([1, 0, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]) */</lang>
[0, 0, 0, 1]) */</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
===Using int Array===
===Using int Array===
{{trans|REXX}}
{{trans|REXX}}
<lang NetRexx>/* NetRexx ************************************************************
<syntaxhighlight lang="netrexx">/* NetRexx ************************************************************
* show identity matrix of size n
* show identity matrix of size n
* I consider m[i,j] to represent the matrix
* I consider m[i,j] to represent the matrix
Line 2,490: Line 2,670:
Say ol
Say ol
End
End
</syntaxhighlight>
</lang>


===Using Indexed String===
===Using Indexed String===
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 2,530: Line 2,710:
displayIdMatrix(createIdMatrix(n))
displayIdMatrix(createIdMatrix(n))
return
return
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc identityMatrix(n: Positive): auto =
<syntaxhighlight lang="nim">proc identityMatrix(n: Positive): auto =
result = newSeq[seq[int]](n)
result = newSeq[seq[int]](n)
for i in 0 ..< result.len:
for i in 0 ..< result.len:
result[i] = newSeq[int](n)
result[i] = newSeq[int](n)
result[i][i] = 1</lang>
result[i][i] = 1</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>class IdentityMatrix {
<syntaxhighlight lang="objeck">class IdentityMatrix {
function : Matrix(n : Int) ~ Int[,] {
function : Matrix(n : Int) ~ Int[,] {
array := Int->New[n,n];
array := Int->New[n,n];
Line 2,572: Line 2,752:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 2,578: Line 2,758:
From the interactive loop (that we call the "toplevel"):
From the interactive loop (that we call the "toplevel"):


<lang ocaml>$ ocaml
<syntaxhighlight lang="ocaml">$ ocaml


# let make_id_matrix n =
# let make_id_matrix n =
Line 2,594: Line 2,774:
[|0.; 1.; 0.; 0.|];
[|0.; 1.; 0.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 0.; 1.|] |]</lang>
[|0.; 0.; 0.; 1.|] |]</syntaxhighlight>


another way:
another way:


<lang ocaml># let make_id_matrix n =
<syntaxhighlight lang="ocaml"># let make_id_matrix n =
Array.init n (fun i ->
Array.init n (fun i ->
Array.init n (fun j ->
Array.init n (fun j ->
Line 2,610: Line 2,790:
[|0.; 1.; 0.; 0.|];
[|0.; 1.; 0.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 0.; 1.|] |]</lang>
[|0.; 0.; 0.; 1.|] |]</syntaxhighlight>


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.
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.
Line 2,617: Line 2,797:
The '''eye''' function create the identity (I) matrix, e.g.:
The '''eye''' function create the identity (I) matrix, e.g.:


<lang octave>I = eye(10)</lang>
<syntaxhighlight lang="octave">I = eye(10)</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (make-identity-matrix n)
(define (make-identity-matrix n)
(map (lambda (i)
(map (lambda (i)
Line 2,627: Line 2,807:


(for-each print (make-identity-matrix 3))
(for-each print (make-identity-matrix 3))
(for-each print (make-identity-matrix 17))</lang>
(for-each print (make-identity-matrix 17))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,653: Line 2,833:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays.
ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
say "a 3x3 identity matrix"
say "a 3x3 identity matrix"
say
say
Line 2,683: Line 2,863:
say line
say line
end i
end i
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height:20ex;overflow:scroll">
<pre style="height:20ex;overflow:scroll">
Line 2,702: Line 2,882:


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
Class SquareMatrix
Class SquareMatrix
'=================
'=================
Line 2,733: Line 2,913:
'...
'...
del M
del M
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Built-in:
Built-in:
<lang parigp>matid(9)</lang>
<syntaxhighlight lang="parigp">matid(9)</syntaxhighlight>


Custom:
Custom:
<lang parigp>matrix(9,9,i,j,i==j)</lang>
<syntaxhighlight lang="parigp">matrix(9,9,i,j,i==j)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>program IdentityMatrix(input, output);
<syntaxhighlight lang="pascal">program IdentityMatrix(input, output);


var
var
Line 2,763: Line 2,943:
writeln;
writeln;
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,776: Line 2,956:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 2,788: Line 2,968:
say "\n$_:";
say "\n$_:";
say join ' ', @$_ for identity_matrix $_;
say join ' ', @$_ for identity_matrix $_;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>4:
<pre>4:
Line 2,812: Line 2,992:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 2,826: Line 3,006:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre style="float:left">
<pre style="float:left">
Line 2,862: Line 3,042:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>
<syntaxhighlight lang="php">
function identity($length) {
function identity($length) {
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1),
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1),
Line 2,871: Line 3,051:
}
}
print_identity(identity(10));
print_identity(identity(10));
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,887: Line 3,067:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de identity (Size)
<syntaxhighlight lang="picolisp">(de identity (Size)
(let L (need Size (1) 0)
(let L (need Size (1) 0)
(make
(make
(do Size
(do Size
(link (copy (rot L))) ) ) ) )</lang>
(link (copy (rot L))) ) ) ) )</syntaxhighlight>
Test:
Test:
<lang PicoLisp>: (identity 3)
<syntaxhighlight lang="picolisp">: (identity 3)
-> ((1 0 0) (0 1 0) (0 0 1))
-> ((1 0 0) (0 1 0) (0 0 1))


Line 2,901: Line 3,081:
(0 0 1 0 0)
(0 0 1 0 0)
(0 0 0 1 0)
(0 0 0 1 0)
(0 0 0 0 1)</lang>
(0 0 0 0 1)</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
identity: procedure (A, n);
identity: procedure (A, n);
declare A(n,n) fixed controlled;
declare A(n,n) fixed controlled;
Line 2,911: Line 3,091:
do i = 1 to n; A(i,i) = 1; end;
do i = 1 to n; A(i,i) = 1; end;
end identity;
end identity;
</syntaxhighlight>
</lang>


=={{header|PostScript}}==
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
<lang PostScript>
% n ident [identity-matrix]
% n ident [identity-matrix]
% create an identity matrix of dimension n*n.
% create an identity matrix of dimension n*n.
Line 2,931: Line 3,111:
]
]
end } def
end } def
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function identity($n) {
function identity($n) {
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row}
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row}
Line 2,941: Line 3,121:
$array = identity 4
$array = identity 4
show $array
show $array
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,949: Line 3,129:
0 0 0 1
0 0 0 1
</pre>
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
$array[0][0]
$array[0][0]
$array[0][1]
$array[0][1]
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,963: Line 3,143:
=={{header|Prolog}}==
=={{header|Prolog}}==
{{Works with|SWi-Prolog}}
{{Works with|SWi-Prolog}}
<lang Prolog>%rotates one list clockwise by one integer
<syntaxhighlight lang="prolog">%rotates one list clockwise by one integer
rotate(Int,List,Rotated) :-
rotate(Int,List,Rotated) :-
integer(Int),
integer(Int),
Line 2,992: Line 3,172:
idmatrix(5,I),
idmatrix(5,I),
maplist(writeln,I).
maplist(writeln,I).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,005: Line 3,185:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>>Procedure identityMatrix(Array i(2), size) ;valid only for size >= 0
<syntaxhighlight lang="purebasic">>Procedure identityMatrix(Array i(2), size) ;valid only for size >= 0
;formats array i() as an identity matrix of size x size
;formats array i() as an identity matrix of size x size
Dim i(size - 1, size - 1)
Dim i(size - 1, size - 1)
Line 3,041: Line 3,221:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 0 0
<pre> 1 0 0
Line 3,055: Line 3,235:
===Nested lists===
===Nested lists===
A simple solution, using nested lists to represent the matrix.
A simple solution, using nested lists to represent the matrix.
<lang python>def identity(size):
<syntaxhighlight lang="python">def identity(size):
matrix = [[0]*size for i in range(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
#matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists
Line 3,065: Line 3,245:
for elements in rows:
for elements in rows:
print elements,
print elements,
print ""</lang>
print ""</syntaxhighlight>


===Nested maps and comprehensions===
===Nested maps and comprehensions===
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Identity matrices by maps and equivalent list comprehensions'''
<syntaxhighlight lang="python">'''Identity matrices by maps and equivalent list comprehensions'''


import operator
import operator
Line 3,129: Line 3,309:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>idMatrix:
<pre>idMatrix:
Line 3,149: Line 3,329:
===Dict of points===
===Dict of points===
A dict of tuples of two ints (x, y) are used to represent the matrix.
A dict of tuples of two ints (x, y) are used to represent the matrix.
<lang python>>>> def identity(size):
<syntaxhighlight lang="python">>>> def identity(size):
... return {(x, y):int(x == y) for x in range(size) for y in range(size)}
... return {(x, y):int(x == y) for x in range(size) for y in range(size)}
...
...
Line 3,159: Line 3,339:
0 0 1 0
0 0 1 0
0 0 0 1
0 0 0 1
>>> </lang>
>>> </syntaxhighlight>


===Numpy===
===Numpy===
A solution using the numpy library
A solution using the numpy library
<lang python>
<syntaxhighlight lang="python">
np.mat(np.eye(size))
np.mat(np.eye(size))
</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang quackery>[ [] swap times
<syntaxhighlight lang="quackery">[ [] swap times
[ 0 i^ of 1 join 0 i of
[ 0 i^ of 1 join 0 i of
join nested join ] ] is identity ( n --> [ )
join nested join ] ] is identity ( n --> [ )


5 identity echo</lang>
5 identity echo</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,181: Line 3,361:
When passed a single scalar argument, <code>diag</code> produces an identity matrix of size given by the scalar. For example:
When passed a single scalar argument, <code>diag</code> produces an identity matrix of size given by the scalar. For example:


<lang rsplus>diag(3)</lang>
<syntaxhighlight lang="rsplus">diag(3)</syntaxhighlight>


produces:
produces:
Line 3,190: Line 3,370:
[3,] 0 0 1</pre>
[3,] 0 0 1</pre>
Or you can also use the method that is shown below
Or you can also use the method that is shown below
<lang rsplus>Identity_matrix=function(size){
<syntaxhighlight lang="rsplus">Identity_matrix=function(size){
x=matrix(0,size,size)
x=matrix(0,size,size)
for (i in 1:size) {
for (i in 1:size) {
Line 3,196: Line 3,376:
}
}
return(x)
return(x)
}</lang>
}</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require math)
(require math)
(identity-matrix 5)
(identity-matrix 5)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,216: Line 3,396:
(formerly Perl 6)
(formerly Perl 6)
{{works with|rakudo|2015-09-15}}
{{works with|rakudo|2015-09-15}}
<lang perl6>sub identity-matrix($n) {
<syntaxhighlight lang="raku" line>sub identity-matrix($n) {
my @id;
my @id;
for flat ^$n X ^$n -> $i, $j {
for flat ^$n X ^$n -> $i, $j {
Line 3,224: Line 3,404:
}
}


.say for identity-matrix(5);</lang>
.say for identity-matrix(5);</syntaxhighlight>
{{out}}
{{out}}
<pre>[1 0 0 0 0]
<pre>[1 0 0 0 0]
Line 3,232: Line 3,412:
[0 0 0 0 1]</pre>
[0 0 0 0 1]</pre>
On the other hand, this may be clearer and/or faster:
On the other hand, this may be clearer and/or faster:
<lang perl6>sub identity-matrix($n) {
<syntaxhighlight lang="raku" line>sub identity-matrix($n) {
my @id = [0 xx $n] xx $n;
my @id = [0 xx $n] xx $n;
@id[$_][$_] = 1 for ^$n;
@id[$_][$_] = 1 for ^$n;
@id;
@id;
}</lang>
}</syntaxhighlight>


Here is yet an other way to do it:
Here is yet an other way to do it:
<lang perl6>sub identity-matrix($n) {
<syntaxhighlight lang="raku" line>sub identity-matrix($n) {
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
}</lang>
}</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang rebol>Red[]
<syntaxhighlight lang="rebol">Red[]


identity-matrix: function [size][
identity-matrix: function [size][
Line 3,255: Line 3,435:
]
]


probe identity-matrix 5</lang>
probe identity-matrix 5</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,273: Line 3,453:


It also tries to display a centered (and easier to read) matrix, &nbsp; along with a title.
It also tries to display a centered (and easier to read) matrix, &nbsp; along with a title.
<lang rexx>/*REXX program creates and displays any sized identity matrix (centered, with title).*/
<syntaxhighlight lang="rexx">/*REXX program creates and displays any sized identity matrix (centered, with title).*/
do k=3 to 6 /* [↓] build and display a sq. matrix.*/
do k=3 to 6 /* [↓] build and display a sq. matrix.*/
call ident_mat k /*build & display a KxK square matrix. */
call ident_mat k /*build & display a KxK square matrix. */
Line 3,302: Line 3,482:
say _ /*display a single line of the matrix. */
say _ /*display a single line of the matrix. */
end /*row*/
end /*row*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default sizes &nbsp; (3 ──► 6) &nbsp; for generating four matrices:}}
{{out|output|text=&nbsp; when using the default sizes &nbsp; (3 ──► 6) &nbsp; for generating four matrices:}}
<pre>
<pre>
Line 3,338: Line 3,518:
===version 2===
===version 2===
An alternative?!
An alternative?!
<lang rexx>
<syntaxhighlight lang="rexx">
/* REXX ***************************************************************
/* REXX ***************************************************************
* show identity matrix of size n
* show identity matrix of size n
Line 3,355: Line 3,535:
Say ol
Say ol
End
End
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,364: Line 3,544:
</pre>
</pre>
This could be a 3-dimensional sparse matrix with one element set:
This could be a 3-dimensional sparse matrix with one element set:
<lang rexx>
<syntaxhighlight lang="rexx">
m.=0
m.=0
m.0=1000 /* the matrix' size */
m.0=1000 /* the matrix' size */
m.4.17.333='Walter'
m.4.17.333='Walter'
</syntaxhighlight>
</lang>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
size = 5
size = 5
im = newlist(size, size)
im = newlist(size, size)
Line 3,397: Line 3,577:
next
next
return alist
return alist
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 3,409: Line 3,589:
Gui version
Gui version


<lang ring>
<syntaxhighlight lang="ring">
# Project : Identity Matrix
# Project : Identity Matrix
# Date : 2022/16/02
# Date : 2022/16/02
Line 3,476: Line 3,656:
next
next
score = 0
score = 0
</syntaxhighlight>
</lang>
Output image:
Output image:


[http://keptarhely.eu/view.php?file=20220216v00xp5u6x.jpeg Identity Matrix]
[http://keptarhely.eu/view.php?file=20220216v00xp5u6x.jpeg Identity Matrix]

=={{header|RPL}}==
{{in}}
<pre>
3 IDN
</pre>
{{out}}
<pre>
1: [[ 1 0 0 ]
[ 0 1 0 ]
[ 0 0 1 ]]
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
===Using Array===
===Using Array===
<lang ruby>def identity(size)
<syntaxhighlight lang="ruby">def identity(size)
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}
end
end
Line 3,489: Line 3,681:
[4,5,6].each do |size|
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s}, ""
puts size, identity(size).map {|r| r.to_s}, ""
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,515: Line 3,707:
</pre>
</pre>
===Using Matrix===
===Using Matrix===
<lang ruby>
<syntaxhighlight lang="ruby">
2.1.1 :001 > require "matrix"
require 'matrix'
p Matrix.identity(5)
=> true
# => 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]]
2.1.1 :002 > Matrix.identity(5)
</syntaxhighlight>
=> 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]]
</lang>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>' formats array im() of size ims
<syntaxhighlight lang="runbasic">' formats array im() of size ims
for ims = 4 to 6
for ims = 4 to 6


Line 3,542: Line 3,733:
print "]"
print "]"
next
next
next ims</lang>
next ims</syntaxhighlight>
{{out}}
{{out}}
<pre>--- Size: 4 ---
<pre>--- Size: 4 ---
Line 3,569: Line 3,760:
Run with command-line containing the matrix size.
Run with command-line containing the matrix size.


<lang rust>
<syntaxhighlight lang="rust">
extern crate num;
extern crate num;
struct Matrix<T> {
struct Matrix<T> {
Line 3,611: Line 3,802:
}
}
}
}
</syntaxhighlight>
</lang>


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


printMatrix(identityMatrix(5))</lang>
printMatrix(identityMatrix(5))</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 0, 0, 0, 0]
<pre>[1, 0, 0, 0, 0]
Line 3,627: Line 3,818:
=={{header|Scheme}}==
=={{header|Scheme}}==
When representing a matrix as a collection of nested lists:
When representing a matrix as a collection of nested lists:
<lang scheme>
<syntaxhighlight lang="scheme">
(define (identity n)
(define (identity n)
(letrec
(letrec
Line 3,643: Line 3,834:
(cons (uvec i 0 '()) acc))))))
(cons (uvec i 0 '()) acc))))))
(idgen 0 '())))
(idgen 0 '())))
</syntaxhighlight>
</lang>
Test program:
Test program:
<lang scheme>
<syntaxhighlight lang="scheme">
(display (identity 4))
(display (identity 4))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,654: Line 3,845:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const type: matrix is array array integer;
const type: matrix is array array integer;
Line 3,686: Line 3,877:
begin
begin
writeMat(identity(6));
writeMat(identity(6));
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 3,699: Line 3,890:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set matrix to buildIdentityMatrix(3)
set matrix to buildIdentityMatrix(3)


Line 3,728: Line 3,919:
return matrixList
return matrixList
end buildIdentityMatrix
end buildIdentityMatrix
</syntaxhighlight>
</lang>
Output for n 3
Output for n 3
<pre>(1,0,0)
<pre>(1,0,0)
Line 3,753: Line 3,944:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func identity_matrix(n) {
<syntaxhighlight lang="ruby">func identity_matrix(n) {
n.of { |i|
n.of { |i|
n.of { |j|
n.of { |j|
Line 3,766: Line 3,957:
say row.join(' ')
say row.join(' ')
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,794: Line 3,985:
=={{header|Sinclair ZX81 BASIC}}==
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM, but for a larger matrix you'll want at least 2k.
Works with 1k of RAM, but for a larger matrix you'll want at least 2k.
<lang zxbasic> 10 INPUT S
<syntaxhighlight lang="zxbasic"> 10 INPUT S
20 DIM M(S,S)
20 DIM M(S,S)
30 FOR I=1 TO S
30 FOR I=1 TO S
Line 3,805: Line 3,996:
100 NEXT J
100 NEXT J
110 PRINT
110 PRINT
120 NEXT I</lang>
120 NEXT I</syntaxhighlight>
{{in}}
{{in}}
<pre>10</pre>
<pre>10</pre>
Line 3,822: Line 4,013:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Pharo Smalltalk}}
{{works with|Pharo Smalltalk}}
<lang smalltalk>(Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString</lang>
<syntaxhighlight lang="smalltalk">(Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,832: Line 4,023:


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>function unitMatrix(n) {
<syntaxhighlight lang="sparkling">function unitMatrix(n) {
return map(range(n), function(k1, v1) {
return map(range(n), function(k1, v1) {
return map(range(n), function(k2, v2) {
return map(range(n), function(k2, v2) {
Line 3,838: Line 4,029:
});
});
});
});
}</lang>
}</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang 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));</lang>
<syntaxhighlight lang="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));</syntaxhighlight>
=={{header|Stata}}==
=={{header|Stata}}==
=== Stata matrix ===
=== Stata matrix ===
<lang stata>. mat a = I(3)
<syntaxhighlight lang="stata">. mat a = I(3)
. mat list a
. mat list a


Line 3,851: Line 4,042:
r1 1
r1 1
r2 0 1
r2 0 1
r3 0 0 1</lang>
r3 0 0 1</syntaxhighlight>


=== Mata ===
=== Mata ===
<lang stata>: I(3)
<syntaxhighlight lang="stata">: I(3)
[symmetric]
[symmetric]
1 2 3
1 2 3
Line 3,861: Line 4,052:
2 | 0 1 |
2 | 0 1 |
3 | 0 0 1 |
3 | 0 0 1 |
+-------------+</lang>
+-------------+</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Line 3,867: Line 4,058:
{{trans|Elixir}}
{{trans|Elixir}}


<lang swift>func identityMatrix(size: Int) -> [[Int]] {
<syntaxhighlight lang="swift">func identityMatrix(size: Int) -> [[Int]] {
return (0..<size).map({i in
return (0..<size).map({i in
return (0..<size).map({ $0 == i ? 1 : 0})
return (0..<size).map({ $0 == i ? 1 : 0})
Line 3,873: Line 4,064:
}
}


print(identityMatrix(size: 5))</lang>
print(identityMatrix(size: 5))</syntaxhighlight>


{{out}}
{{out}}
Line 3,880: Line 4,071:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates identityMatrix
templates identityMatrix
def n: $;
def n: $;
Line 3,889: Line 4,080:
$identity... -> '|$(1);$(2..last)... -> ', $;';|
$identity... -> '|$(1);$(2..last)... -> ', $;';|
' -> !OUT::write
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,901: Line 4,092:
=={{header|Tcl}}==
=={{header|Tcl}}==
When representing a matrix as a collection of nested lists:
When representing a matrix as a collection of nested lists:
<lang tcl>proc I {rank {zero 0.0} {one 1.0}} {
<syntaxhighlight lang="tcl">proc I {rank {zero 0.0} {one 1.0}} {
set m [lrepeat $rank [lrepeat $rank $zero]]
set m [lrepeat $rank [lrepeat $rank $zero]]
for {set i 0} {$i < $rank} {incr i} {
for {set i 0} {$i < $rank} {incr i} {
Line 3,907: Line 4,098:
}
}
return $m
return $m
}</lang>
}</syntaxhighlight>
Or alternatively with the help of the tcllib package for rectangular data structures:
Or alternatively with the help of the tcllib package for rectangular data structures:
{{tcllib|struct::matrix}}
{{tcllib|struct::matrix}}
<lang tcl>package require struct::matrix
<syntaxhighlight lang="tcl">package require struct::matrix


proc I {rank {zero 0.0} {one 1.0}} {
proc I {rank {zero 0.0} {one 1.0}} {
Line 3,922: Line 4,113:
}
}
return $m
return $m
}</lang>
}</syntaxhighlight>
Demonstrating the latter:
Demonstrating the latter:
<lang tcl>set m [I 5 0 1] ;# Integer 0/1 for clarity of presentation
<syntaxhighlight lang="tcl">set m [I 5 0 1] ;# Integer 0/1 for clarity of presentation
puts [$m format 2string]</lang>
puts [$m format 2string]</syntaxhighlight>
{{out}}
{{out}}
<pre>1 0 0 0 0
<pre>1 0 0 0 0
Line 3,934: Line 4,125:


=={{header|TypeScript}}==
=={{header|TypeScript}}==
<lang typescript>
<syntaxhighlight lang="typescript">
function identity(n) {
function identity(n) {
if (n < 1) return "Not defined";
if (n < 1) return "Not defined";
Line 3,949: Line 4,140:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>int main (string[] args) {
<syntaxhighlight lang="vala">int main (string[] args) {
if (args.length < 2) {
if (args.length < 2) {
print ("Please, input an integer > 0.\n");
print ("Please, input an integer > 0.\n");
Line 3,976: Line 4,167:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Private Function Identity(n As Integer) As Variant
<syntaxhighlight lang="vb">Private Function Identity(n As Integer) As Variant
Dim I() As Integer
Dim I() As Integer
ReDim I(n - 1, n - 1)
ReDim I(n - 1, n - 1)
Line 3,986: Line 4,177:
Next j
Next j
Identity = I
Identity = I
End Function</lang>
End Function</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
build_matrix(7)
build_matrix(7)


Line 4,019: Line 4,210:
Next
Next
End Sub
End Sub
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 4,035: Line 4,226:
'''Alternate version'''
'''Alternate version'''


<lang vbscript>
<syntaxhighlight lang="vbscript">
n = 8
n = 8


Line 4,051: Line 4,242:
Identity = a
Identity = a
End Function
End Function
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,066: Line 4,257:
=={{header|Visual Basic}}==
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
{{works with|Visual Basic|6}}
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
'------------
'------------
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte()
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte()
Line 4,104: Line 4,295:


End Sub
End Sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>10000
<pre>10000
Line 4,124: Line 4,315:


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
im ^(%^\@table ^(@+ =) @to)
im ^(%^\@table ^(@+ =) @to)


!im 4
!im 4
}</lang>
}</syntaxhighlight>
Returns:
Returns:
<pre>[[1 0 0 0]
<pre>[[1 0 0 0]
Line 4,138: Line 4,329:
{{libheader|Wren-matrix}}
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/matrix" for Matrix
<syntaxhighlight lang="wren">import "./matrix" for Matrix
import "/fmt" for Fmt
import "./fmt" for Fmt


var numRows = 10 // say
var numRows = 10 // say
Fmt.mprint(Matrix.identity(numRows), 2, 0)</lang>
Fmt.mprint(Matrix.identity(numRows), 2, 0)</syntaxhighlight>


{{out}}
{{out}}
Line 4,159: Line 4,350:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
def IntSize = 4; \number of bytes in an integer
def IntSize = 4; \number of bytes in an integer
int Matrix, Size, I, J;
int Matrix, Size, I, J;
Line 4,175: Line 4,366:
CrLf(0);
CrLf(0);
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,189: Line 4,380:
=={{header|zkl}}==
=={{header|zkl}}==
Using lists of lists:
Using lists of lists:
<lang zkl>fcn idMatrix(n){
<syntaxhighlight lang="zkl">fcn idMatrix(n){
m:=(0).pump(n,List.createLong(n).write,0)*n;
m:=(0).pump(n,List.createLong(n).write,0)*n;
m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0));
m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0));
Line 4,195: Line 4,386:
}
}
idMatrix(5).println();
idMatrix(5).println();
idMatrix(5).pump(Console.println);</lang>
idMatrix(5).pump(Console.println);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,208: Line 4,399:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|Applesoft_BASIC}}
{{trans|Applesoft_BASIC}}
<lang zxbasic>10 INPUT "Matrix size: ";size
<syntaxhighlight lang="zxbasic">10 INPUT "Matrix size: ";size
20 GO SUB 200: REM Identity matrix
20 GO SUB 200: REM Identity matrix
30 FOR r=1 TO size
30 FOR r=1 TO size
Line 4,223: Line 4,414:
240 LET i(i,i)=1
240 LET i(i,i)=1
250 NEXT i
250 NEXT i
260 RETURN</lang>
260 RETURN</syntaxhighlight>

Latest revision as of 11:19, 25 January 2024

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

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



Related tasks



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/2017
INDENMAT 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                exit
NN       EQU    10                 parameter n  (90=>32K)
N        DC     A(NN)              n
LL       DS     F                  n*n*4
PG       DC     CL(NN)' '          buffer
XDEC     DS     CL12               temp
DYNA     DSECT
A        DS     F                  a(n,n)
         YREGS
         END    INDENMAT
Output:
1000000000
0100000000
0010000000
0001000000
0000100000
0000010000
0000001000
0000000100
0000000010
0000000001

Action!

PROC CreateIdentityMatrix(BYTE ARRAY mat,BYTE size)
  CARD pos
  BYTE i,j

  pos=0
  FOR i=1 TO size
  DO
    FOR j=1 TO size
    DO
      IF i=j THEN 
        mat(pos)=1
      ELSE
        mat(pos)=0
      FI
      pos==+1
    OD
  OD
RETURN

PROC PrintMatrix(BYTE ARRAY mat,BYTE size)
  CARD pos
  BYTE i,j,v

  pos=0
  FOR i=1 TO size
  DO
    FOR j=1 TO size
    DO
      v=mat(pos)
      IF j=size THEN
        PrintF("%I%E",v)
      ELSE
        PrintF("%I ",v)
      FI
      pos==+1
    OD
  OD
RETURN

PROC Main()
  BYTE size
  BYTE ARRAY mat(400)
  BYTE LMARGIN=$52,old

  old=LMARGIN
  LMARGIN=0 ;remove left margin on the screen

  DO
    Print("Get size of matrix [1-20] ")
    size=InputB()
  UNTIL size>=1 AND size<=20
  OD

  CreateIdentityMatrix(mat,size)
  PrintMatrix(mat,size)

  LMARGIN=old ;restore left margin on the screen
RETURN
Output:

Screenshot from Atari 8-bit computer

Get size of matrix [1-20] 13
1 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 1 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 1 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 1 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 1 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 1 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 1

Ada

When using floating point matrices in Ada 2005+ the function is defined as "Unit_Matrix" in Ada.Numerics.Generic_Real_Arrays. As a generic package it can work with user defined floating point types, or the predefined Short_Real_Arrays, Real_Arrays, and Long_Real_Arrays initializations. As seen below, the first indices of both dimensions can also be set since Ada array indices do not arbitrarily begin with a particular number.

--  As prototyped in the Generic_Real_Arrays specification:
--  function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix;
-- For the task:
mat : Real_Matrix := Unit_Matrix(5);

For prior versions of Ada, or non floating point types its back to basics:

type Matrix is array(Positive Range <>, Positive Range <>) of Integer;
mat : Matrix(1..5,1..5) := (others => (others => 0));
--  then after the declarative section:
for i in mat'Range(1) loop mat(i,i) := 1; end loop;

ALGOL 68

Works with: ALGOL 68 version Revision 1 - one extension to language used - PRAGMA READ - a non standard feature similar to C's #include directive.
Works with: ALGOL 68G version Any - tested with release algol68g-2.8.

Note: The generic vector and matrix code should be moved to a more generic page.

File: prelude/vector_base.a68

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

# Define some generic vector initialisation and printing operations #

COMMENT REQUIRES:
  MODE SCAL = ~ # a scalar, eg REAL #;
  FORMAT scal fmt := ~;
END COMMENT

INT vec lwb := 1, vec upb := 0;
MODE VECNEW = [vec lwb:vec upb]SCAL; MODE VEC = REF VECNEW;
FORMAT vec fmt := $"("n(vec upb-vec lwb)(f(scal fmt)", ")f(scal fmt)")"$;

PRIO INIT = 1;

OP INIT = (VEC self, SCAL scal)VEC: (
  FOR col FROM LWB self TO UPB self DO self[col]:= scal OD;
  self
);

# ZEROINIT: defines the additive identity #
OP ZEROINIT = (VEC self)VEC: 
  self INIT SCAL(0);

OP REPR = (VEC self)STRING: (
  FILE f; STRING s; associate(f,s);
  vec lwb := LWB self; vec upb := UPB self;
  putf(f, (vec fmt, self)); close(f);
  s
);

SKIP

File: prelude/matrix_base.a68

# -*- coding: utf-8 -*- #

# Define some generic matrix initialisation and printing operations #

COMMENT REQUIRES:
  MODE SCAL = ~ # a scalar, eg REAL #;
  MODE VEC = []SCAL;
  FORMAT scal fmt := ~;
  et al.
END COMMENT

INT mat lwb := 1, mat upb := 0;
MODE MATNEW = [mat lwb:mat upb, vec lwb: vec upb]SCAL; MODE MAT = REF MATNEW;
FORMAT mat fmt = $"("n(vec upb-vec lwb)(f(vec fmt)","lx)f(vec fmt)")"l$;

PRIO DIAGINIT = 1;

OP INIT = (MAT self, SCAL scal)MAT: (
  FOR row FROM LWB self TO UPB self DO self[row,] INIT scal OD;
  self
);

# ZEROINIT: defines the additive identity #
OP ZEROINIT = (MAT self)MAT: 
  self INIT SCAL(0);

OP REPR = (MATNEW self)STRING: (
  FILE f; STRING s; associate(f,s);
  vec lwb := 2 LWB self; vec upb := 2 UPB self;
  mat lwb :=   LWB self; mat upb :=   UPB self;
  putf(f, (mat fmt, self)); close(f);
  s
);

OP DIAGINIT = (MAT self, VEC diag)MAT: (
  ZEROINIT self;
  FOR d FROM LWB diag TO UPB diag DO self[d,d]:= diag[d] OD;
# or alternatively using TORRIX ...
  DIAG self := diag;
#
  self
);

# ONEINIT: defines the multiplicative identity #
OP ONEINIT = (MAT self)MAT: (
  ZEROINIT self DIAGINIT (LOC[LWB self:UPB self]SCAL INIT SCAL(1))
# or alternatively using TORRIX ...
  (DIAG out) VECINIT SCAL(1)
#
);

SKIP

File: prelude/matrix_ident.a68

# -*- coding: utf-8 -*- #

PRIO IDENT = 9; # The same as I for COMPLex #

OP IDENT = (INT lwb, upb)MATNEW:
  ONEINIT LOC [lwb:upb,lwb:upb]SCAL;

OP IDENT = (INT upb)MATNEW: # default lwb is 1 #
  1 IDENT upb;

SKIP

File: prelude/matrix.a68

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

PR READ "prelude/vector_base.a68" PR;
PR READ "prelude/matrix_base.a68" PR;
PR READ "prelude/matrix_ident.a68" PR;

SKIP

File: test/matrix_ident.a68

#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #

MODE SCAL = REAL;
FORMAT scal fmt := $g(-3,1)$;

PR READ "prelude/matrix.a68" PR;

print(REPR IDENT 4)
Output:
((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))

ALGOL W

begin
    % set m to an identity matrix of size s                                  %
    procedure makeIdentity( real    array m ( *, * )
                          ; integer value s
                          ) ;
        for i := 1 until s do begin
            for j := 1 until s do m( i, j ) := 0.0;
            m( i, i ) := 1.0
        end makeIdentity ;

    % test the makeIdentity procedure                                        %
    begin
        real array id5( 1 :: 5, 1 :: 5 );
        makeIdentity( id5, 5 );
        r_format := "A"; r_w := 6; r_d := 1; % set output format for reals   %
        for i := 1 until 5 do begin
            write();
            for j := 1 until 5 do writeon( id5( i, j ) )
        end for_i ;
    end text

end.

Amazing Hopper

#include <jambo.h>

Main
    Dim( 10,10 ) as eyes 'UMatrix'
    
    Printnl ' "UNIT MATRIX:\n", UMatrix '
    
    /* Classical method */
    
    Dim (10,10) as zeros (ZM)
    i=1
    Iterator ( ++i, #(i<=10), #( ZM[i,i]=1 ) )
    Printnl ' "UNIT MATRIX:\n", ZM '

    /* unit matrix non square*/
    Dim ( 5,8 ) as eyes 'rare unit matrix'
    
    Printnl ' "RARE UNIT MATRIX:\n", rare unit matrix '
End
Output:
UNIT MATRIX:
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

UNIT MATRIX:
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

RARE UNIT MATRIX:
1,0,0,0,0,0,0,0
0,1,0,0,0,0,0,0
0,0,1,0,0,0,0,0
0,0,0,1,0,0,0,0
0,0,0,0,1,0,0,0

APL

Making an identity matrix in APL involves the outer product of the equality function.

For a square matrix of 3:

    ∘.=3
1 0 0
0 1 0
0 0 1

For a function that makes an identity matrix:

    ID{∘.=}
    ID 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

An tacit function can be defined with one of the following equivalent lines:

    ID∘.=
    ID∘.=⍳

There is a more idomatic way however:

    ID{  ρ 1, ρ0}

AppleScript

--------------------- IDENTITY MATRIX ----------------------

-- identityMatrix :: Int -> [(0|1)]
on identityMatrix(n)
    set xs to enumFromTo(1, n)
    
    script row
        on |λ|(x)
            script col
                on |λ|(i)
                    if i = x then
                        1
                    else
                        0
                    end if
                end |λ|
            end script
            map(col, xs)
        end |λ|
    end script
    
    map(row, xs)
end identityMatrix


--------------------------- TEST ---------------------------
on run
    
    unlines(map(showList, ¬
        identityMatrix(5)))
    
end run


-------------------- GENERIC FUNCTIONS ---------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m  n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        lst
    else
        {}
    end if
end enumFromTo


-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, delim}
    set s to xs as text
    set my text item delimiters to dlm
    s
end intercalate


-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map


-- Lift 2nd class handler function into 1st class script wrapper 
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


-- showList :: [a] -> String
on showList(xs)
    "[" & intercalate(", ", map(my str, xs)) & "]"
end showList


-- str :: a -> String
on str(x)
    x as string
end str


-- unlines :: [String] -> String
on unlines(xs)
    -- A single string formed by the intercalation
    -- of a list of strings with the newline character.
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set s to xs as text
    set my text item delimiters to dlm
    s
end unlines
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]

Simple alternative

on indentityMatrix(n)
    set digits to {}
    set m to n - 1
    repeat (n + m) times
        set end of digits to 0
    end repeat
    set item n of digits to 1
    
    set matrix to {}
    repeat with i from n to 1 by -1
        set end of matrix to items i thru (i + m) of digits
    end repeat
    
    return matrix
end indentityMatrix

return indentityMatrix(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}}

Arturo

identityM: function [n][
    result: array.of: @[n n] 0
    loop 0..dec n 'i -> result\[i]\[i]: 1
    return result
]

loop 4..6 'sz [
    print sz
    loop identityM sz => print
    print ""
]
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

BASIC

Applesoft BASIC

100 INPUT "MATRIX SIZE:"; SIZE%
110 GOSUB 200"IDENTITYMATRIX
120 FOR R = 0 TO SIZE%
130     FOR C = 0 TO SIZE%
140         LET S$ = CHR$(13)
150         IF C < SIZE% THEN S$ = " "
160         PRINT IM(R, C) S$; : NEXT C, R
170 END

200 REMIDENTITYMATRIX SIZE%
210 LET SIZE% = SIZE% - 1
220 DIM IM(SIZE%, SIZE%)
230 FOR I = 0 TO SIZE%
240     LET IM(I, I) = 1 : NEXT I
250 RETURN :IM

Commodore BASIC

Translation of: Applesoft BASIC
Works with: Commodore BASIC version 2.0
100 INPUT "MATRIX SIZE:"; SIZE
110 GOSUB 200: REM IDENTITYMATRIX
120 FOR R = 0 TO SIZE
130 FOR C = 0 TO SIZE
140 S$ = CHR$(13)
150 IF C < SIZE THEN S$ = ""
160 PRINT MID$(STR$(IM(R, C)),1)S$;:REM MID$ STRIPS LEADING SPACES
170 NEXT C, R
180 END
190 REM *******************************
200 REM IDENTITYMATRIX SIZE%
210 SIZE = SIZE - 1
220 DIM IM(SIZE, SIZE)
230 FOR I = 0 TO SIZE
240     IM(I, I) = 1
250 NEXT I
260 RETURN

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 i
END 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 i
END SUB

DO
    INPUT "Enter size of matrix "; n
LOOP UNTIL n > 0

DIM identity(1 TO n, 1 TO n)

CALL inicio(identity())
CALL mostrar(identity())

BASIC256

Translation of: FreeBASIC
arraybase 1
do
    input "Enter size of matrix: ", n
until n > 0

dim identity(n, n) fill 0  #we fill everything with 0

# enter 1s in diagonal elements
for i =  1 to n
    identity[i, i] = 1
next 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 i
else
    print "Matrix is too big to display on 80 column console"
end if
Output:
Same as FreeBASIC entry.

XBasic

Works with: Windows XBasic
Translation of: FreeBASIC
PROGRAM  "Identity matrix"
VERSION	"0.0000"

DECLARE FUNCTION  Entry ()

FUNCTION  Entry ()
  DO
    n = SBYTE(INLINE$("Enter size of matrix: "))
  LOOP UNTIL n > 0

  DIM identity[n, n] '' all zero by default

  ' enter 1s in diagonal elements
  FOR i =  1 TO n
    identity[i, i] = 1
  NEXT 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 i
  ELSE
    PRINT "Matrix is too big to display on 80 column console"
  END IF

END FUNCTION
END PROGRAM
Output:
Same as FreeBASIC entry.

Yabasic

Translation of: FreeBASIC
repeat
    input "Enter size of matrix: " n
until n > 0 

dim identity(n, n) // all zero by default

// enter 1s in diagonal elements
for i =  1 to n
    identity(i, i) = 1
next 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 i
else 
    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"
//
(* ****** ****** *)

extern
fun
idmatrix{n:nat}(n: size_t(n)): matrixref(int, n, n)
implement
idmatrix(n) =
matrixref_tabulate_cloref<int> (n, n, lam(i, j) => bool2int0(i = j))

(* ****** ****** *)

implement
main0 () =
{
//
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  |
                    --

AWK

# syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
    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

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\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp
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

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#a?dr@{(D!)\/1\/^^bx\/[+}m[e!

Shorter alternative:

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

BQN

⍝ Using table
Eye ← =⌜˜∘↕
•Show Eye 3

⍝ Using reshape
Eye1 ← {𝕩‿𝕩⥊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.

Try it here!

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

Delphi

program IdentityMatrix;

// Modified from the Pascal version

{$APPTYPE CONSOLE}

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

EasyLang

proc idmat lng . mat[][] .
   len mat[][] lng
   for i to lng
      len mat[i][] lng
      mat[i][i] = 1
   .
.
idmat 4 m[][]
print m[][]

Eiffel

class
	APPLICATION

inherit
	ARGUMENTS

create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
		    dim : INTEGER -- Dimension of the identity matrix
		do
		    from dim := 1 until dim > 10 loop
		    	print_matrix( identity_matrix(dim) )
				dim := dim + 1
				io.new_line
			end

		end

feature -- Access

	identity_matrix(dim : INTEGER) : ARRAY2[REAL_64]

		require
			dim > 0
		local
			matrix : ARRAY2[REAL_64]
			i : INTEGER
		do

			create matrix.make_filled (0.0, dim, dim)
			from i := 1 until i > dim loop
				matrix.put(1.0, i, i)
				i := i + 1
			end

			Result := matrix
		end

	print_matrix(matrix : ARRAY2[REAL_64])
		local
			i, j : INTEGER
		do
			from i := 1 until i > matrix.height loop
				print("[ ")
				from j := 1 until j > matrix.width loop
					print(matrix.item (i, j))
					print(" ")
					j := j + 1
				end
				print("]%N")
				i := i + 1
			end
		end

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

Elena

ELENA 6.x :

import extensions;
import system'routines;
import system'collections;
 
public program()
{
    var n := console.write("Enter the matrix size:").readLine().toInt();
 
    var identity := new Range(0, n).selectBy::(i => new Range(0,n).selectBy::(j => (i == j).iif(1,0) ).summarize(new ArrayList())) 
                         .summarize(new ArrayList());
 
    identity.forEach::
        (row) { console.printLine(row.asEnumerable()) }
}
Output:
Enter the matrix size:3
1,0,0
0,1,0
0,0,1

Elixir

defmodule Matrix do
  def identity(n) do
    Enum.map(0..n-1, fn i ->
      for j <- 0..n-1, do: (if i==j, do: 1, else: 0)
    end)
  end
end

IO.inspect Matrix.identity(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]]

Erlang

%% Identity Matrix in Erlang for the Rosetta Code Wiki.
%% Implemented by Arjun Sunel

-module(identity_matrix).
-export([square_matrix/2 , identity/1]).

square_matrix(Size, Elements) ->
    [[Elements(Column, Row) || Column <- lists:seq(1, Size)] || Row <- lists:seq(1, Size)].

identity(Size) ->
    square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).

ERRE

PROGRAM IDENTITY

!$DYNAMIC
DIM A[0,0]

BEGIN
  PRINT(CHR$(12);) ! CLS
  INPUT("Matrix size",N%)
  !$DIM A[N%,N%]
  FOR I%=1 TO N% DO
    A[I%,I%]=1
  END FOR
! print matrix
  FOR I%=1 TO N% DO
    FOR J%=1 TO N% DO
      WRITE("###";A[I%,J%];)
    END FOR
    PRINT
  END FOR
END PROGRAM

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:

(See LAMBDA: The ultimate Excel worksheet function)

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:

fx =IDMATRIX(A2)
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-identity
6 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 "; n
Loop Until n > 0 

Dim identity(1 To n, 1 To n) As Integer '' all zero by default

' enter 1s in diagonal elements
For i As Integer =  1 To n
  identity(i, i) = 1
Next

' 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 i
Else 
  Print "Matrix is too big to display on 80 column console"
End If

Print
Print "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.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Test cases

FutureBasic

include "NSLog.incl"

local fn IdentityMatrix( n as NSInteger ) as CFStringRef
NSInteger i, j
CFMutableArrayRef tempArr = fn MutableArrayWithCapacity( n )
CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )

for i = 0 to n - 1
MutableArrayRemoveAllObjects( tempArr )
for j = 0 to n - 1
MutableArrayInsertObjectAtIndex( tempArr, @"0", j )
next
MutableArrayReplaceObjectAtIndex( tempArr, @"1", i )
MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) )
MutableStringAppendString( mutStr, @"\n" )
next
end 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-in
IdentityMat(3);

# One can also specify the base ring
IdentityMat(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]

Haskell

matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]

And a function to show matrix pretty:

showMat :: [[Int]] -> String
showMat = unlines . map (unwords . map show)


*Main> putStr $ showMat $ matId 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

We could alternatively bypassing the syntactic sugaring of list comprehension notation, and use a bind function directly:

idMatrix :: Int -> [[Int]]
idMatrix n =
  let xs = [1 .. n]
  in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]

or reduce the number of terms a little to:

idMatrix :: Int -> [[Int]]
idMatrix n =
  let xs = [1 .. n]
  in (\x -> fromEnum . (x ==) <$> xs) <$> xs

main :: IO ()
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 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

Icon and Unicon

This code works for Icon and Unicon.

link matrix
procedure main(argv)
    if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.")
    matrix1 := identity_matrix(argv[1], argv[1])
    write_matrix(&output,matrix1)
end
Output:
->im 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
->

IS-BASIC

100 PROGRAM "Identity.bas"
110 INPUT PROMPT "Enter size of matrix: ":N
120 NUMERIC A(1 TO N,1 TO N)
130 CALL INIT(A)
140 CALL WRITE(A)
150 DEF INIT(REF T)
160   FOR I=LBOUND(T,1) TO UBOUND(T,1)
170     FOR J=LBOUND(T,2) TO UBOUND(T,2)
180       LET T(I,J)=0
190     NEXT
200     LET T(I,I)=1
210   NEXT
220 END DEF
230 DEF WRITE(REF T)
240   FOR I=LBOUND(T,1) TO UBOUND(T,1)
250     FOR J=LBOUND(T,2) TO UBOUND(T,2)
260       PRINT T(I,J);
270     NEXT
280     PRINT
290   NEXT
300 END DEF

J

   = i. 4          NB. create an Identity matrix of size 4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
   makeI=: =@i.    NB. define as a verb with a user-defined name
   makeI 5         NB. create an 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

Java

public class PrintIdentityMatrix {

    public static void main(String[] args) {
        int n = 5;
        int[][] array = new int[n][n];

        IntStream.range(0, n).forEach(i -> array[i][i] = 1);

        Arrays.stream(array)
                .map((int[] a) -> Arrays.toString(a))
                .forEach(System.out::println);
    }
}
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]

JavaScript

ES5

function idMatrix(n) {
    return Array.apply(null, new Array(n))
        .map(function (x, i, xs) {
            return xs.map(function (_, k) {
                return i === k ? 1 : 0;
            })
        });
}

ES6

(() => {

    // identityMatrix :: Int -> [[Int]]
    const identityMatrix = n =>
        Array.from({
            length: n
        }, (_, i) => Array.from({
            length: n
        }, (_, j) => i !== j ? 0 : 1));


    // ----------------------- TEST ------------------------
    return identityMatrix(5)
        .map(JSON.stringify)
        .join('\n');
})();
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]

jq

Construction

def identity(n):
  [range(0;n) | 0] as $row
  | reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );

Example:

identity(4)

produces:

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

Using matrix/2

Using the definition of matrix/2 at Create_a_two-dimensional_array_at_runtime#jq:

def identity(n): 
  reduce range(0;n) as $i
    (0 | matrix(n;n); .[$i][$i] = 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:
promt$ jsish -u identityMatrix.jsi
[PASS] identityMatrix.jsi

Julia

I is an object of type UniformScaling, representing an identity matrix of any size, boolean by default, that can be multiplied by a scalar

using LinearAlgebra
unitfloat64matrix = 1.0I

UniformScaling object can be used as a function to construct a Diagonal matrix of given size, that can be converted to a full matrix using collect

using LinearAlgebra
diagI3 = 1.0I(3)
fullI3 = collect(diagI3)

The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are

using LinearAlgebra
fullI3 = Matrix{Float64}(I, 3, 3)
fullI3 = Array{Float64}(I, 3, 3)
fullI3 = Array{Float64,2}(I, 3, 3)
fullI3 = zeros(3,3) + I

K

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

Kotlin

// version 1.0.6

fun main(args: Array<String>) {
    print("Enter size of matrix : ")
    val n = readLine()!!.toInt()
    println()
    val identity = Array(n) { IntArray(n) } // create n x n matrix of integers

    // enter 1s in diagonal elements
    for(i in 0 until n) identity[i][i] = 1

    // print identity matrix if n <= 40
    if (n <= 40) 
        for (i in 0 until n) println(identity[i].joinToString(" "))
    else 
        println("Matrix is too big to display on 80 column console")
}

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

Lambdatalk

{def identity
 {lambda {:n}
  {A.new {S.map {{lambda {:n :i} 
   {A.new {S.map {{lambda {:i :j}
                          {if {= :i :j} then 1 else 0} } :i}  
          {S.serie 0 :n}}}} :n} 
         {S.serie 0 :n}} }}}
-> identity

{identity 2}
-> [[1,0],[0,1]]

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


Lang5

: identity-matrix
    dup iota 'A set

    : i.(*) A in ;
    [1] swap append reverse A swap reshape 'i. apply
    ;

5 identity-matrix .
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  ]
]

LFE

(defun identity
  ((`(,m ,n))
   (identity m n))
  ((m)
   (identity m m)))

(defun identity (m n)
  (lists:duplicate m (lists:duplicate n 1)))

From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix:

> (identity 3)
((1 1 1) (1 1 1) (1 1 1))
> (identity 3 3)
((1 1 1) (1 1 1) (1 1 1))
> (identity '(3 3))
((1 1 1) (1 1 1) (1 1 1))

LSL

To test it yourself; rez a box on the ground, and add the following as a New Script.

default {
	state_entry() {
		llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
		llOwnerSay("Please Enter a Dimension for an Identity Matrix.");
	}
	listen(integer iChannel, string sName, key kId, string sMessage) {
		llOwnerSay("You entered "+sMessage+".");
		list lMatrix = [];
		integer x = 0;
		integer n = (integer)sMessage;
		for(x=0 ; x<n*n ; x++) {
			lMatrix += [(integer)(((x+1)%(n+1))==1)];
		}
		//llOwnerSay("["+llList2CSV(lMatrix)+"]");
		for(x=0 ; x<n ; x++) {
			llOwnerSay("["+llList2CSV(llList2ListStrided(lMatrix, x*n, (x+1)*n-1, 1))+"]");
		}
	}
}
Output:
You: 0
Identity_Matrix: You entered 0.
You: 1
Identity_Matrix: You entered 1.
Identity_Matrix: [1]
You: 3
Identity_Matrix: You entered 3.
Identity_Matrix: [1, 0, 0]
Identity_Matrix: [0, 1, 0]
Identity_Matrix: [0, 0, 1]
You: 5
Identity_Matrix: You entered 5.
Identity_Matrix: [1, 0, 0, 0, 0]
Identity_Matrix: [0, 1, 0, 0, 0]
Identity_Matrix: [0, 0, 1, 0, 0]
Identity_Matrix: [0, 0, 0, 1, 0]
Identity_Matrix: [0, 0, 0, 0, 1]

Lua

function identity_matrix (size)
        local m = {}
        for i = 1, size do
                m[i] = {}
                for j = 1, size do
                        m[i][j] = i == j and 1 or 0
                end
        end
        return m
end

function print_matrix (m)
        for i = 1, #m do
                print(table.concat(m[i], " "))
        end
end

print_matrix(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

Maple

One of a number of ways to do this:

> LinearAlgebra:-IdentityMatrix( 4 );
                           [1    0    0    0]
                           [                ]
                           [0    1    0    0]
                           [                ]
                           [0    0    1    0]
                           [                ]
                           [0    0    0    1]

Here, for instance, is another, in which the entries are (4-byte) floats.

> Matrix( 4, shape = scalar[1], datatype = float[4] );
                         [1.    0.    0.    0.]
                         [                    ]
                         [0.    1.    0.    0.]
                         [                    ]
                         [0.    0.    1.    0.]
                         [                    ]
                         [0.    0.    0.    1.]

Yet another, with 2-byte integer entries:

> Matrix( 4, shape = identity, datatype = integer[ 2 ] );
                           [1    0    0    0]
                           [                ]
                           [0    1    0    0]
                           [                ]
                           [0    0    1    0]
                           [                ]
                           [0    0    0    1]

MathCortex

I = eye(10)

Mathematica / Wolfram Language

IdentityMatrix[4]

MATLAB / Octave

The eye function create the identity (I) matrix, e.g.:

I = eye(10)

Maxima

ident(4);
/* matrix([1, 0, 0, 0],
          [0, 1, 0, 0],
          [0, 0, 1, 0],
          [0, 0, 0, 1]) */

NetRexx

Using int Array

Translation of: REXX
/* NetRexx ************************************************************
* show identity matrix of size n
* I consider m[i,j] to represent the matrix
* 09.07.2013 Walter Pachl (translated from REXX Version 2)
**********************************************************************/
options replace format comments java crossref symbols binary

Parse Arg n .
If n='' then n=5
Say 'Identity Matrix of size' n '(m[i,j] IS the Matrix)'
m=int[n,n] -- Allocate 2D square array at run-time
Loop i=0 To n-1 -- Like Java, arrays in NetRexx start at 0
  ol=''
  Loop j=0 To n-1
    m[i,j]=(i=j)
    ol=ol m[i,j]
    End
  Say ol
  End

Using Indexed String

/* NetRexx */
options replace format comments java crossref symbols nobinary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method createIdMatrix(n) public static
  DIM_ = 'DIMENSION'
  m = 0 -- Indexed string to hold matrix; default value for all elements is zero
  m[DIM_] = n
  loop i = 1 to n -- NetRexx indexed strings don't have to start at zero
    m[i, i] = 1   -- set this diagonal element to 1
    end i
  return m
  
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method displayIdMatrix(m) public static
  DIM_ = 'DIMENSION'
  if \m.exists(DIM_) then signal RuntimeException('Matrix dimension not set')
  n = m[DIM_]
  loop i = 1 to n
    ol = ''
    loop j = 1 To n
      ol = ol m[i, j]
      end j
    say ol
    end i
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
  parse arg n .
  if n = '' then n = 5
  say 'Identity Matrix of size' n
  displayIdMatrix(createIdMatrix(n))
  return

Nim

proc identityMatrix(n: Positive): auto =
  result = newSeq[seq[int]](n)
  for i in 0 ..< result.len:
    result[i] = newSeq[int](n)
    result[i][i] = 1

Objeck

class IdentityMatrix {
  function : Matrix(n : Int) ~ Int[,] {
    array := Int->New[n,n];
    
    for(row:=0; row<n; row+=1;){
      for(col:=0; col<n; col+=1;){
        if(row = col){
          array[row, col] := 1;
        }
        else{
          array[row,col] := 0;
        };
      };
    };
    return array;
  }
  
  function : PrintMatrix(array : Int[,]) ~ Nil {
    sizes := array->Size();
    for(row:=0; row<sizes[0]; row+=1;){
      for(col:=0; col<sizes[1]; col+=1;){
        value := array[row,col];
        "{$value} \t"->Print();
      };
      '\n'->PrintLine();
    };
  }
  
  function : Main(args : String[]) ~ Nil {
    PrintMatrix(Matrix(5));
  }
}

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"
say
call printMatrix createIdentityMatrix(3)
say
say "a 5x5 identity matrix"
say
call 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 4
show $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 integer
rotate(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 integers
rotate(LoInts,LoLists,Rotated) :-
	is_list(LoInts),
	maplist(rotate,LoInts,LoLists,Rotated).

%helper function
append_(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("")
  Next
EndProcedure

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 -> c
def compose(g):
    '''Right to left function composition.'''
    return lambda f: lambda x: g(f(x))


# curry :: ((a, b) -> c) -> a -> b -> c
def 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 0
0 1 0 0
0 0 1 0
0 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 n
Say 'Identity Matrix of size' n '(m.i.j IS the Matrix)'
m.=0
Do 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.=0
m.0=1000 /* the matrix' size */
m.4.17.333='Walter'

Ring

size = 5
im = newlist(size, size)
identityMatrix(size, im)
for r = 1 to size
    for c = 1 to size
        see im[r][c]
    next
    see nl
next 
 
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   : <calmosoft@gmail.com>

load "stdlib.ring"
load "guilib.ring"

size = 8
C_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:

Identity Matrix

RPL

Input:
3 IDN
Output:
1:          [[ 1 0 0 ]
             [ 0 1 0 ]
            [ 0 0 1 ]]

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

require 'matrix'
p 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 ims
for 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 "]"
 next
next 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 it
end repeat

set matrix to buildIdentityMatrix(17)

repeat for each item in matrix
	put it
end 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 matrixList
end 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 J
110 PRINT
120 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  c3
r1   1
r2   0   1
r3   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]]

Tailspin

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:

set m [I 5 0 1]    ;# Integer 0/1 for clarity of presentation
puts [$m format 2string]
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

TypeScript

function identity(n) {
    if (n < 1) return "Not defined";
    else if (n == 1) return 1;
    else {
        var idMatrix:number[][];
        for (var i: number = 0; i < n; i++) {
            for (var j: number = 0; j < n; j++) {
                if (i != j) idMatrix[i][j] = 0;
                else idMatrix[i][j] = 1;
            }            
        }
        return idMatrix;
    }
}

Vala

int main (string[] args) {
	if (args.length < 2) {
		print ("Please, input an integer > 0.\n");
		return 0;
	}
	var n = int.parse (args[1]);
	if (n <= 0) {
		print ("Please, input an integer > 0.\n");
		return 0;
	}
	int[,] array = new int[n, n];
	for (var i = 0; i < n; i ++) {
		for (var j = 0; j < n; j ++) {
			if (i == j) array[i,j] = 1;
			else array[i,j] = 0;
		}
	}
	for (var i = 0; i < n; i ++) {
		for (var j = 0; j < n; j ++) {
			print ("%d ", array[i,j]);
		}
		print ("\b\n");
	}
	return 0;
}

VBA

Private Function Identity(n As Integer) As Variant
    Dim I() As Integer
    ReDim I(n - 1, n - 1)
    For j = 0 To n - 1
        I(j, j) = 1
    Next j
    Identity = I
End Function

VBScript

build_matrix(7)

Sub build_matrix(n)
	Dim matrix()
	ReDim matrix(n-1,n-1)
	i = 0
	'populate the matrix
	For row = 0 To n-1
		For col = 0 To n-1
			If col = i Then
				matrix(row,col) = 1
			Else
				matrix(row,col) = 0
			End If	
		Next
		i = i + 1
	Next
	'display the matrix
	For row = 0 To n-1
		For col = 0 To n-1
			If col < n-1 Then
				WScript.StdOut.Write matrix(row,col) & " "
			Else
				WScript.StdOut.Write matrix(row,col)
			End If
		Next
		WScript.StdOut.WriteLine
	Next
End Sub
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


Alternate version

n = 8

arr = Identity(n)

for i = 0 to n-1
    for j = 0 to n-1
        wscript.stdout.Write arr(i,j) & " "
    next
    wscript.stdout.writeline
next

Function Identity (size)
    Execute Replace("dim a(#,#):for i=0 to #:for j=0 to #:a(i,j)=0:next:a(i,i)=1:next","#",size-1)
    Identity = a
End Function
Output:
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1

Visual Basic

Works with: Visual Basic version 6
Option Explicit
'------------
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte()
Dim i As Long
Dim b() As Byte

  Size = Size - 1
  ReDim b(0 To Size, 0 To Size)
  'at this point, the matrix is allocated and
  'all elements are initialized to 0 (zero)
  For i = 0 To Size
    b(i, i) = 1   'set diagonal elements to 1
  Next i
  BuildIdentityMatrix = b
  
End Function
'------------
Sub IdentityMatrixDemo(ByVal Size As Long)
Dim b() As Byte
Dim i As Long, j As Long

  b() = BuildIdentityMatrix(Size)
  For i = LBound(b(), 1) To UBound(b(), 1)
    For j = LBound(b(), 2) To UBound(b(), 2)
      Debug.Print CStr(b(i, j));
    Next j
  Debug.Print
  Next i

End Sub
'------------
Sub Main()

  IdentityMatrixDemo 5
  Debug.Print
  IdentityMatrixDemo 10

End Sub
Output:
10000
01000
00100
00010
00001

1000000000
0100000000
0010000000
0001000000
0000100000
0000010000
0000001000
0000000100
0000000010
0000000001

Wortel

@let {
  im ^(%^\@table ^(@+ =) @to)

  !im 4
}

Returns:

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

Wren

Library: Wren-matrix
Library: Wren-fmt
import "./matrix" for Matrix
import "./fmt" for Fmt

var numRows = 10 // say
Fmt.mprint(Matrix.identity(numRows), 2, 0)
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|

XPL0

include c:\cxpl\codes;
def IntSize = 4;                        \number of bytes in an integer
int Matrix, Size, I, J;

[Text(0, "Size: ");  Size:= IntIn(0);
Matrix:= Reserve(Size*IntSize);         \reserve memory for 2D integer array
for I:= 0 to Size-1 do
        Matrix(I):= Reserve(Size*IntSize);
for J:= 0 to Size-1 do                  \make array an identity matrix
    for I:= 0 to Size-1 do
        Matrix(I,J):= if I=J then 1 else 0;
for J:= 0 to Size-1 do                  \display the result
    [for I:= 0 to Size-1 do
        [IntOut(0, Matrix(I,J));  ChOut(0, ^ )];
    CrLf(0);
    ];
]
Output:
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 

zkl

Using lists of lists:

fcn idMatrix(n){
   m:=(0).pump(n,List.createLong(n).write,0)*n;
   m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0));
   m
}
idMatrix(5).println();
idMatrix(5).pump(Console.println);
Output:
L(L(1,0,0,0,0),L(0,1,0,0,0),L(0,0,1,0,0),L(0,0,0,1,0),L(0,0,0,0,1))
L(1,0,0,0,0)
L(0,1,0,0,0)
L(0,0,1,0,0)
L(0,0,0,1,0)
L(0,0,0,0,1)

ZX Spectrum Basic

Translation of: Applesoft_BASIC
10 INPUT "Matrix size: ";size
20 GO SUB 200: REM Identity matrix
30 FOR r=1 TO size
40 FOR c=1 TO size
50 LET s$=CHR$ 13
60 IF c<size THEN LET s$=" "
70 PRINT i(r,c);s$;
80 NEXT c
90 NEXT r
100 STOP 
200 REM Identity matrix size
220 DIM i(size,size)
230 FOR i=1 TO size
240 LET i(i,i)=1
250 NEXT i
260 RETURN