Identity matrix: Difference between revisions

m
m (alignment)
imported>Arakov
(224 intermediate revisions by 96 users not shown)
Line 1:
{{task}} [[Category:Matrices]]
[[Category:Matrices]]
Build an [[wp:identity matrix|identity matrix]] of a size known at runtime. An identity matrix is a square matrix, of size ''n'' × ''n'', where the diagonal elements are all 1s, and the other elements are all 0s.
 
;Task:
Build an   [[wp:identity matrix|identity matrix]]   of a size known at run-time.
 
 
An ''identity matrix'' is a square matrix of size '''''n'' × ''n''''',
<br>where the diagonal elements are all '''1'''s (ones),
<br>and all the other elements are all '''0'''s (zeroes).
 
 
<math>I_n = \begin{bmatrix}
Line 9 ⟶ 18:
0 & 0 & 0 & \cdots & 1 \\
\end{bmatrix}</math>
 
 
;Related tasks:
* &nbsp; [[Spiral matrix]]
* &nbsp; [[Zig-zag matrix]]
* &nbsp; [[Ulam_spiral_(for_primes)]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">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)</syntaxhighlight>
 
{{out}}
<pre>
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
</pre>
 
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* 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</syntaxhighlight>
{{out}}
<pre>
1000000000
0100000000
0010000000
0001000000
0000100000
0000010000
0000001000
0000000100
0000000010
0000000001
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Identity_matrix.png Screenshot from Atari 8-bit computer]
<pre>
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
</pre>
 
=={{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.
<langsyntaxhighlight Adalang="ada">-- 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);</langsyntaxhighlight>
For prior versions of Ada, or non floating point types its back to basics:
<langsyntaxhighlight Adalang="ada">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;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - one extension to language used - PRAGMA READ - a non standard feature similar to C's #include directive.}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.8 algol68g-2.8].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''Note:''' The generic vector and matrix code should be moved to a more generic page.
 
'''File: prelude/vector_base.a68'''<syntaxhighlight lang="algol68">#!/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</syntaxhighlight>'''File: prelude/matrix_base.a68'''<syntaxhighlight lang="algol68"># -*- 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</syntaxhighlight>'''File: prelude/matrix_ident.a68'''<syntaxhighlight lang="algol68"># -*- 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</syntaxhighlight>'''File: prelude/matrix.a68'''<syntaxhighlight lang="algol68">#!/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</syntaxhighlight>'''File: test/matrix_ident.a68'''<syntaxhighlight lang="algol68">#!/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)</syntaxhighlight>
{{out}}
<pre>
((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))
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">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.</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}}==
Making an identity matrix in APL involves the outer product of the inequalityequality function.
 
For a square matrix of 3:
<langsyntaxhighlight lang="apl">
∘.=/⍳¨3 3⍨⍳3
1 0 0
0 1 0
0 0 1
</syntaxhighlight>
</lang>
 
For a function that makes an identity matrix:
<langsyntaxhighlight lang="apl">
ID←{∘.=/⍳¨ ⍵ ⍵⍨⍳⍵}
ID 5
1 0 0 0 0
Line 42 ⟶ 447:
0 0 0 1 0
0 0 0 0 1
</syntaxhighlight>
</lang>
An tacit function can be defined with one of the following equivalent lines:
 
<syntaxhighlight lang="apl">
ID←∘.=⍨⍳
ID←⍳∘.=⍳
</syntaxhighlight>
 
There is a more idomatic way however:
<langsyntaxhighlight lang="apl">
ID←{⍵ ⍵ ρ 1, ⍵ρ0}
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="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</syntaxhighlight>
{{Out}}
<pre>[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]</pre>
----
===Simple alternative===
<syntaxhighlight lang="applescript">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)</syntaxhighlight>
 
{{output}}
<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}}==
 
<syntaxhighlight lang="rebol">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 ""
]</syntaxhighlight>
 
{{out}}
 
<pre>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</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="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
</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
{{trans|Applesoft BASIC}}
{{works with|Commodore BASIC|2.0}}
<syntaxhighlight lang="gwbasic">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</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|IS-BASIC}}
<syntaxhighlight lang="qbasic">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())</syntaxhighlight>
 
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">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</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}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="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] *)
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="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 "--"
}</syntaxhighlight>
 
{{out}}
<pre>
--
| 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 |
--
</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
Line 69 ⟶ 891:
exit(0)
}
</syntaxhighlight>
</lang>
<p>{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5</p>
<pre>
<p>output:</p>
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
</pre>
 
=={{header|Bash}}==
<syntaxhighlight lang="bash">
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
</syntaxhighlight>
{{out}} for command: ./scriptname 5
<pre>
1 0 0 0 0
Line 82 ⟶ 916:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INPUT "Enter size of matrix: " size%
PROCidentitymatrix(size%, im())
FOR r% = 0 TO size%-1
Line 98 ⟶ 932:
m(i%,i%) = 1
NEXT
ENDPROC</langsyntaxhighlight>
 
=={{header|Beads}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
<pre>
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
</pre>
 
=={{header|Burlesque}}==
Line 104 ⟶ 959:
Neither very elegant nor short but it'll do
 
<langsyntaxhighlight lang="burlesque">
blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp
1 0 0 0 0 0
Line 112 ⟶ 967:
0 0 0 0 1 0
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:
 
<langsyntaxhighlight lang="burlesque">
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e!
</syntaxhighlight>
</lang>
 
Shorter alternative:
 
<syntaxhighlight lang="burlesque">
blsq ) 6 ^^^^10\/**XXcy\/co.+sp
</syntaxhighlight>
 
=={{header|BQN}}==
<syntaxhighlight lang="text">⍝ Using table
Eye ← =⌜˜∘↕
•Show Eye 3
 
⍝ Using reshape
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0}
Eye1 5</syntaxhighlight>
<syntaxhighlight lang="text">┌─
╵ 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
</syntaxhighlight>
 
<code>Eye</code> generates an identity matrix using a table of equality for [0,n).
 
<code>Eye1</code> reshapes a boolean vector to generate the matrix.
 
[https://mlochbaum.github.io/BQN/try.html#code=4o2dIFVzaW5nIHRhYmxlCkV5ZSDihpAgPeKMnMuc4oiY4oaVCuKAolNob3cgRXllIDMKCuKNnSBVc2luZyByZXNoYXBlCkV5ZTEg4oaQIHvwnZWp4oC/8J2VqeKlijHiiL7wnZWp4qWKMH0KRXllMSA1 Try it here!]
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdlib.h>
#include <stdio.h>
Line 129 ⟶ 1,018:
exit(EXIT_FAILURE);
}
signed int rowsize = atoi(argv[1]);
if (rowsize < 0) {
printf("Dimensions of matrix cannot be negative\n");
exit(EXIT_FAILURE);
}
volatile int numElements = rowsize * rowsize;
if (numElements < rowsize) {
printf("Squaring %d caused result to overflow to %d.\n", rowsize, numElements);
Line 141 ⟶ 1,030:
int** matrix = calloc(numElements, sizeof(int*));
if (!matrix) {
printf("Failed to allocate %d elements of %dld bytes each\n", numElements, sizeof(int*));
abort();
}
Line 147 ⟶ 1,036:
matrix[row] = calloc(numElements, sizeof(int));
if (!matrix[row]) {
printf("Failed to allocate %d elements of %dld bytes each\n", numElements, sizeof(int));
abort();
}
Line 160 ⟶ 1,049:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp}}==
<syntaxhighlight lang="csharp">
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();
}
}
}
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
 
=={{header|C++}}==
{{libheader|STL}}
<langsyntaxhighlight lang="cpp">template<class T>
class matrix
{
Line 211 ⟶ 1,148:
return 0;
}
</syntaxhighlight>
</lang>
{{libheader|boost}}
<langsyntaxhighlight lang="cpp">
#include <boost/numeric/ublas/matrix.hpp>
 
Line 237 ⟶ 1,174:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 248 ⟶ 1,185:
</pre>
 
=={{header|C sharpClio}}==
<syntaxhighlight lang="clio">fn identity-matrix n:
<lang csharp>
[0:n] -> * fn i:
using System;
[0:n] -> * if = i: 1
using System.Linq;
else: 0
 
5 -> identity-matrix -> * print</syntaxhighlight>
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();
}
}
}
</lang>
{{out}}
<pre>
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
</pre>
 
=={{header|Clojure}}==
Line 300 ⟶ 1,197:
 
The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g.
<langsyntaxhighlight lang="clojure"> '( (0 1) (2 3) )
</syntaxhighlight>
</lang>
, then care to remove the vec function.
<langsyntaxhighlight lang="clojure">(defn identity-matrix [n]
(let [row (conj (repeat (dec n) 0) 1)]
(vec
Line 309 ⟶ 1,206:
(vec
(reduce conj (drop i row ) (take i row)))))))
</syntaxhighlight>
</lang>
{{out}}
Sample output:
<langsyntaxhighlight 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]]
</syntaxhighlight>
</lang>
 
The following is a more idomatic definition that utilizes infinite lists and cycling.
<langsyntaxhighlight lang="clojure">
(defn identity-matrix [n]
(take n
(partition n (dec n)
(cycle (conj (repeat (dec n) 0) 1)))))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 327 ⟶ 1,224:
Common Lisp provides multi-dimensional arrays.
 
<langsyntaxhighlight lang="lisp">(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))
</syntaxhighlight>
</lang>
 
{{out}}
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))
 
<syntaxhighlight lang="lisp">(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)))
</syntaxhighlight>
 
{{out}}
<pre>
> (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))
</pre>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
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.
</syntaxhighlight>
Execute: ^Q Algebras.Do<br/>
{{out}}
<pre>
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
</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.traits;
 
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
Line 367 ⟶ 1,326:
 
// auto id3 = matId!(const int)(2); // cant't compile
}</langsyntaxhighlight>
{{out}}
<pre>[[1, 0, 0, 0, 0],
Line 379 ⟶ 1,338:
[0, 0, 1]]</pre>
 
=={{header|Delphi}}==
<syntaxhighlight lang="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.</syntaxhighlight>
{{out}}
<pre>
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
</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}}==
<syntaxhighlight lang="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
</syntaxhighlight>
 
{{out}}
<pre>
[ 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 ]
</pre>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">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()) }
}</syntaxhighlight>
{{out}}
<pre>
Enter the matrix size:3
1,0,0
0,1,0
0,0,1
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="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)</syntaxhighlight>
 
{{out}}
<pre>
[[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]]
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%% Identity Matrix in Erlang for the Rosetta Code Wiki.
%% Implemented by Arjun Sunel
 
Line 391 ⟶ 1,518:
 
identity(Size) ->
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="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
</syntaxhighlight>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
function IdentityMatrix(n)
$ X:=zeros(n,n);
Line 403 ⟶ 1,554:
$ return X;
$endfunction
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="euler math toobox">
<lang Euler Math Toobox>
>function IdentityMatrix (n:index)
$ return setdiag(zeros(n,n),0,1);
$endfunction
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="text">
>id(5)
</syntaxhighlight>
</lang>
 
=={{header|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 [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
 
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">IDMATRIX
=LAMBDA(n,
LET(
ixs, SEQUENCE(n, n, 0, 1),
x, MOD(ixs, n),
y, QUOTIENT(ixs, n),
 
IF(x = y,
1,
0
)
)
)</syntaxhighlight>
 
{{Out}}
 
The formula in cell B2 below populates the '''B2:F6''' grid:
 
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="6" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=IDMATRIX(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="font-weight:bold" | N
| colspan="5" style="font-weight:bold" | Identity matrix
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right; font-weight:bold" | 5
| style="text-align:right; background-color:#cbcefb" | 1
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
|
| style="text-align:right" | 0
| style="text-align:right" | 1
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
|
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 1
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
|
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 1
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
|
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 1
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="text-align:right; font-weight:bold" | 3
| style="text-align:right" | 1
| style="text-align:right" | 0
| style="text-align:right" | 0
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
|
| style="text-align:right" | 0
| style="text-align:right" | 1
| style="text-align:right" | 0
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
|
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 1
|
|
|}
 
=={{header|F Sharp|F#}}==
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)
</syntaxhighlight>
</lang>
 
{{out}}
Example output:
<syntaxhighlight lang="fsharp">
<lang FSharp>
ident 10;;
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]
Line 434 ⟶ 1,703:
[0; 0; 0; 0; 0; 0; 0; 0; 1; 0]
[0; 0; 0; 0; 0; 0; 0; 0; 0; 1]]
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
'''USE: math.matrices'''
<syntaxhighlight lang="factor">USING: math.matrices prettyprint ;
IN: scratchpad '''6 identity-matrix .'''
 
{
6 <identity-matrix> .</syntaxhighlight>
{ 1 0 0 0 0 0 }
{{out}}
{ 0 1 0 0 0 0 }
<pre>
{ 0 0 1 0 0 0 }
{
{ 0 0 0 1 0 0 }
{ 1 0 0 0 0 1 0 }
{ 0 1 0 0 0 0 1 }
{ 0 0 1 0 0 0 }
}
{ 0 0 0 1 0 0 }
{ 0 0 0 0 1 0 }
{ 0 0 0 0 0 1 }
}</pre>
 
=={{header|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:
<div style="overflow:auto;white-space:nowrap;background-color:ivory;border:1px dashed rgb(47, 111, 171); padding:12px"><b><code>
<span style="color:gray">#APPTYPE CONSOLE</span>
 
<span style="color:red">TYPE</span> M4F <span style="color:green">' Matrix 4F</span>
:m11 <span style="color:blueviolet">AS SINGLE</span>
:m12 <span style="color:blueviolet">AS SINGLE</span>
:m13 <span style="color:blueviolet">AS SINGLE</span>
:m14 <span style="color:blueviolet">AS SINGLE</span>
:m21 <span style="color:blueviolet">AS SINGLE</span>
:m22 <span style="color:blueviolet">AS SINGLE</span>
:m23 <span style="color:blueviolet">AS SINGLE</span>
:m24 <span style="color:blueviolet">AS SINGLE</span>
:m31 <span style="color:blueviolet">AS SINGLE</span>
:m32 <span style="color:blueviolet">AS SINGLE</span>
:m33 <span style="color:blueviolet">AS SINGLE</span>
:m34 <span style="color:blueviolet">AS SINGLE</span>
:m41 <span style="color:blueviolet">AS SINGLE</span>
:m42 <span style="color:blueviolet">AS SINGLE</span>
:m43 <span style="color:blueviolet">AS SINGLE</span>
:m44 <span style="color:blueviolet">AS SINGLE</span><br>
<span style="color:red">END TYPE</span>
 
<span style="color:blueviolet">DIM</span> m <span style="color:blueviolet">AS</span> M4F <span style="color:green">' DIM zeros out any variable automatically</span>
 
<span style="color:blue">PRINT</span> <span style="color:maroon">"Matrix 'm' is identity: "</span>, <span style="color:blue">IIF</span>(<span style="color:blue">MATRIXISIDENTITY</span>(<span style="color:maroon">@</span>m), <span style="color:maroon">"TRUE"</span>, <span style="color:maroon">"FALSE"</span>) <span style="color:green">' is matrix an identity?</span><br>
<span style="color:blue">MATRIXIDENTITY</span>(<span style="color:maroon">@</span>m) <span style="color:green">' set matrix to identity</span><br>
<span style="color:blue">PRINT</span> <span style="color:maroon">"Matrix 'm' is identity: "</span>, <span style="color:blue">IIF</span>(<span style="color:blue">MATRIXISIDENTITY</span>(<span style="color:maroon">@</span>m), <span style="color:maroon">"TRUE"</span>, <span style="color:maroon">"FALSE"</span>) <span style="color:green">' is matrix an identity?</span>
 
<span style="color:blue">PAUSE</span>
</code></b></div>
{{out}}
<div style="overflow:auto;white-space:nowrap;background-color:black;border:1px dashed rgb(167, 215, 249); padding:12px"><b><code>
<span style="color:white">Matrix 'm' is identity: FALSE<br>
Matrix 'm' is identity: TRUE<br><br>
Press any key to continue...</span>
</code></b></div>
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">
Func Identity(n)=Array id[n,n];[id]:=[1].
 
Identity(7)
[id]
</syntaxhighlight>
{{out}}
<pre>
[[ 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 ]]</pre>
 
=={{header|Forth}}==
{{libheader|Forth Scientific Library}}
{{works with|gforth|0.7.9_20170308}}
<syntaxhighlight lang="forth">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</syntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95}}
 
<langsyntaxhighlight lang="fortran">
program identitymatrix
 
Line 475 ⟶ 1,824:
 
end program identitymatrix
</syntaxhighlight>
</lang>
 
===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.
<syntaxhighlight lang="fortran"> 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</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:
<syntaxhighlight lang="fortran"> DO 1 I = 1,N
DO 1 J = 1,N
1 A(I,J) = (I/J)*(J/I)</syntaxhighlight>
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.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="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</syntaxhighlight>
Sample input/output
{{out}}
<pre>
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
</pre>
 
=={{header|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.
 
<syntaxhighlight lang="frink">n = parseInt[input["Enter matrix dimension as an integer: "]]
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</syntaxhighlight>
 
{{out}}
<pre>
Enter matrix dimension as an integer: 3
┌ ┐
│1 0 0│
│ │
│0 1 0│
│ │
│0 0 1│
└ ┘
</pre>
 
=={{header|FunL}}==
<syntaxhighlight lang="funl">def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 )
 
println( identity(3) )</syntaxhighlight>
 
{{out}}
 
<pre>
((1, 0, 0), (0, 1, 0), (0, 0, 1))
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Identity_matrix}}
 
'''Solution'''
 
[[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>
 
 
=={{header|GAP}}==
<syntaxhighlight lang="gap"># Built-in
IdentityMat(3);
 
# One can also specify the base ring
IdentityMat(3, Integers mod 10);</syntaxhighlight>
 
 
 
=={{header|Go}}==
===Library gonum/mat===
'''2D.''' Representation as a slice of slices, but based on a single allocated array to maintain locality.
<langsyntaxhighlight lang="go">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)))
}</syntaxhighlight>
{{out}}
<pre>
⎡1 0 0⎤
⎢0 1 0⎥
⎣0 0 1⎦
</pre>
 
===Library go.matrix===
A somewhat earlier matrix library for Go.
<syntaxhighlight lang="go">package main
 
import (
"fmt"
 
mat "github.com/skelterjohn/go.matrix"
)
 
func main() {
fmt.Println(mat.Eye(3))
}</syntaxhighlight>
{{out}}
<pre>
{1, 0, 0,
0, 1, 0,
0, 0, 1}
</pre>
 
===From scratch===
'''Simplest: ''' A matrix as a slice of slices, allocated separately.
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 489 ⟶ 2,066:
func I(n int) [][]float64 {
m := make([][]float64, n)
a := make([]float64, n*n)
for i := 0; i < n; i++ {
a := make([]float64, n)
a[i] = 1
m[i] = a[:n]
a = a[n:]
}
return m
}</langsyntaxhighlight>
{{out}}
No special formatting method used.
Line 502 ⟶ 2,078:
[[1 0 0] [0 1 0] [0 0 1]]
</pre>
 
'''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.
'''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"
 
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
}</syntaxhighlight>
 
{{out}}
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.
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 510 ⟶ 2,110:
 
func main() {
fmt.Println(I(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 {
Line 520 ⟶ 2,136:
}
return m
}</langsyntaxhighlight>
{{out}}
<pre>
[1 0 0 0 1 0 0 0 1]
1 0 0
</pre>
0 1 0
'''Library.'''
0 0 1
<lang go>package main
 
import (
"fmt"
 
mat "github.com/skelterjohn/go.matrix"
)
 
func main() {
fmt.Println(mat.Eye(3))
}</lang>
{{out}}
A nice library includes formatted output.
<pre>
{1, 0, 0,
0, 1, 0,
0, 0, 1}
</pre>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def makeIdentityMatrix = { n ->
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">(2..6).each { order ->
def iMatrix = makeIdentityMatrix(order)
iMatrix.each { println it }
println()
}</langsyntaxhighlight>
 
{{out}}
Output:
<pre>[1, 0]
[0, 1]
Line 585 ⟶ 2,185:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]</langsyntaxhighlight>
And a function to show matrix pretty:
<langsyntaxhighlight lang="haskell">showMat :: [[Int]] -> String
showMat = unlines . map (unwords . map show)</langsyntaxhighlight>
 
 
<langsyntaxhighlight lang="haskell">*Main> putStr $ showMat $ matId 9
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
Line 601 ⟶ 2,201:
0 0 0 0 0 0 0 1 0
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:
 
<syntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]]
idMatrix n =
let xs = [1 .. n]
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</syntaxhighlight>
 
or reduce the number of terms a little to:
<syntaxhighlight lang="haskell">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</syntaxhighlight>
{{Out}}
<pre>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</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
 
This code works for Icon and Unicon.
<syntaxhighlight lang="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
</syntaxhighlight>
 
{{out}}
<pre>
->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
->
</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> = i. 4 NB. create an Identity matrix of size 4
1 0 0 0
0 1 0 0
Line 615 ⟶ 2,283:
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">public class PrintIdentityMatrix {
<lang Java>
public class IdentityMatrix {
 
public static int[]void main(String[] matrix(int nargs) {
int[][] array = new int[ n][n] = 5;
int[][] array = new int[n][n];
 
for(int row=0; row<n; row++){
IntStream.range(0, n).forEach(i -> array[i][i] = 1);
for(int col=0; col<n; col++){
 
if(row == col){
Arrays.stream(array)
array[row][col] = 1;
.map((int[] a) -> Arrays.toString(a))
}
.forEach(System.out::println);
else{
}
array[row][col] = 0;
}</syntaxhighlight>
}
 
}
{{out}}
}
<pre>[1, 0, 0, 0, 0]
return array;
[0, 1, 0, 0, 0]
}
[0, 0, 1, 0, 0]
public static void printMatrix(int[][] array){
[0, 0, 0, 1, 0]
for(int row=0; row<array.length; row++){
[0, 0, 0, 0, 1]</pre>
for(int col=0; col<array[row].length; col++){
 
System.out.print(array[row][col] + "\t");
=={{header|JavaScript}}==
}
 
System.out.println();
===ES5===
}
 
}
<syntaxhighlight lang="javascript">function idMatrix(n) {
public static void main (String []args){
return Array.apply(null, new Array(n))
printMatrix(matrix(5));
.map(function (x, i, xs) {
}
return xs.map(function (_, k) {
return i === k ? 1 : 0;
})
});
}</syntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
 
// 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');
})();</syntaxhighlight>
{{Out}}
<pre>[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]</pre>
 
=={{header|jq}}==
===Construction===
<syntaxhighlight lang="jq">def identity(n):
[range(0;n) | 0] as $row
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</syntaxhighlight>
Example:
<syntaxhighlight lang="jq">identity(4)</syntaxhighlight>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]]:
<syntaxhighlight lang="jq">def identity(n):
reduce range(0;n) as $i
(0 | matrix(n;n); .[$i][$i] = 1);
</syntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* 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;
}
By Sani Yusuf @saniyusuf.
</lang>
 
provide('identityMatrix', 1);
Output:
 
<pre>1 0 0 0 0
if (Interp.conf('unitTest')) {
0 1 0 0 0
; identityMatrix(0);
0 0 1 0 0
; identityMatrix(1);
0 0 0 1 0
; identityMatrix(2);
0 0 0 0 1</pre>
; 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!=
*/</syntaxhighlight>
 
{{out}}
<pre>promt$ jsish -u identityMatrix.jsi
[PASS] identityMatrix.jsi</pre>
 
=={{header|Julia}}==
<tt>I</tt> is an object of type UniformScaling,
The <tt>eye</tt> function takes an integer argument and returns a square identity matrix of that size.
representing an identity matrix of any size,
<lang Julia>
boolean by default, that can be multiplied by a scalar
eye(3)
<syntaxhighlight lang="julia">using LinearAlgebra
</lang>
unitfloat64matrix = 1.0I</syntaxhighlight>
This returns:
<pre>
3x3 Float64 Array:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
</pre>
 
UniformScaling object can be used as a function to construct a Diagonal
If you want to take the size from the commandline:
matrix of given size, that can be converted to a full matrix using <tt>collect</tt>
<lang Julia>
<syntaxhighlight lang="julia">using LinearAlgebra
eye(int(readline(STDIN)))
diagI3 = 1.0I(3)
</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
You can also can also call <tt>eye(m,n)</tt> to create an M-by-N identity matrix.
 
For example:
<syntaxhighlight lang="julia">using LinearAlgebra
<lang Julia>
fullI3 = Matrix{Float64}(I, 3, 3)
eye(2,3)
fullI3 = Array{Float64}(I, 3, 3)
</lang>
fullI3 = Array{Float64,2}(I, 3, 3)
results in:
fullI3 = zeros(3,3) + I</syntaxhighlight>
 
=={{header|K}}==
 
<syntaxhighlight lang="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)
</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// 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")
}</syntaxhighlight>
Sample input/output
{{out}}
<pre>
Enter size of matrix : 5
2x3 Float64 Array:
 
1.0 0.0 0.0
1 0. 0 1.0 0.0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{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]]
</syntaxhighlight>
 
 
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">: identity-matrix
dup iota 'A set
 
: i.(*) A in ;
[1] swap append reverse A swap reshape 'i. apply
;
 
5 identity-matrix .</syntaxhighlight>
{{out}}
<pre>[
[ 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 ]
]</pre>
 
=={{header|LFE}}==
 
<syntaxhighlight lang="lisp">
(defun identity
((`(,m ,n))
(identity m n))
((m)
(identity m m)))
 
(defun identity (m n)
(lists:duplicate m (lists:duplicate n 1)))
</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="lisp">
> (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))
 
</syntaxhighlight>
 
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
<langsyntaxhighlight LSLlang="lsl">default {
state_entry() {
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
Line 708 ⟶ 2,547:
}
}
}</langsyntaxhighlight>
{{out}}
Output:
<pre>You: 0
Identity_Matrix: You entered 0.
Line 727 ⟶ 2,566:
Identity_Matrix: [0, 0, 0, 1, 0]
Identity_Matrix: [0, 0, 0, 0, 1]</pre>
 
=={{header|Lang5}}==
<lang lang5>: identity-matrix
dup iota 'A set
 
: i.(*) A in ;
[1] swap append reverse A swap reshape 'i. apply
;
 
5 identity-matrix .</lang>
{{out}}
<pre>[
[ 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 ]
]</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function identity_matrix (size)
local m = {}
Line 765 ⟶ 2,586:
end
 
print_matrix(identity_matrix(5))</langsyntaxhighlight>
{{out}}
Output:
<pre>
1 0 0 0 0
Line 776 ⟶ 2,597:
=={{header|Maple}}==
One of a number of ways to do this:
<syntaxhighlight lang="maple">
<lang Maple>
> LinearAlgebra:-IdentityMatrix( 4 );
[1 0 0 0]
Line 785 ⟶ 2,606:
[ ]
[0 0 0 1]
</syntaxhighlight>
</lang>
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] );
[1. 0. 0. 0.]
Line 796 ⟶ 2,617:
[ ]
[0. 0. 0. 1.]
</syntaxhighlight>
</lang>
Yet another, with 2-byte integer entries:
<syntaxhighlight lang="maple">
<lang Maple>
> Matrix( 4, shape = identity, datatype = integer[ 2 ] );
[1 0 0 0]
Line 807 ⟶ 2,628:
[ ]
[0 0 0 1]
</syntaxhighlight>
</lang>
 
=={{header|MathematicaMathCortex}}==
<syntaxhighlight lang="mathcortex">I = eye(10)</syntaxhighlight>
<lang Mathematica>IdentityMatrix[4]</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">IdentityMatrix[4]</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
The '''eye''' function create the identity (I) matrix, e.g.:
 
<langsyntaxhighlight MATLABlang="matlab">I = eye(10)</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">ident(4);
/* matrix([1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]) */</langsyntaxhighlight>
 
=={{header|NetRexx}}==
===Using int Array===
{{trans|REXX}}
<syntaxhighlight lang="netrexx">/* 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
</syntaxhighlight>
 
===Using Indexed String===
<syntaxhighlight lang="netrexx">/* 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
</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class IdentityMatrix {
function : Matrix(n : Int) ~ Int[,] {
array := Int->New[n,n];
Line 857 ⟶ 2,752:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 863 ⟶ 2,758:
From the interactive loop (that we call the "toplevel"):
 
<langsyntaxhighlight lang="ocaml">$ ocaml
 
# let make_id_matrix n =
Line 879 ⟶ 2,774:
[|0.; 1.; 0.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 0.; 1.|] |]</langsyntaxhighlight>
 
another way:
 
<langsyntaxhighlight lang="ocaml"># let make_id_matrix n =
Array.init n (fun i ->
Array.init n (fun j ->
Line 895 ⟶ 2,790:
[|0.; 1.; 0.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 0.; 1.|] |]</langsyntaxhighlight>
 
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 902 ⟶ 2,797:
The '''eye''' function create the identity (I) matrix, e.g.:
 
<langsyntaxhighlight lang="octave">I = eye(10)</langsyntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(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))</syntaxhighlight>
{{out}}
<pre>
(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)</pre>
 
=={{header|ooRexx}}==
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
Line 936 ⟶ 2,863:
say line
end i
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre style="height:20ex;overflow:scroll">
a 3x3 identity matrix
Line 955 ⟶ 2,882:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
Class SquareMatrix
'=================
Line 986 ⟶ 2,913:
'...
del M
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Built-in:
<syntaxhighlight lang="parigp">matid(9)</syntaxhighlight>
 
Custom:
<syntaxhighlight lang="parigp">matrix(9,9,i,j,i==j)</syntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program IdentityMatrix(input, output);
 
var
Line 1,009 ⟶ 2,943:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
Output:
<pre>
% ./IdentityMatrix
Line 1,021 ⟶ 2,955:
</pre>
 
=={{header|PARI/GPPerl}}==
<syntaxhighlight lang="perl">use strict;
Built-in:
use warnings;
<lang parigp>matid(9)</lang>
use feature 'say';
 
sub identity_matrix {
Custom:
my($n) = shift() - 1;
<lang parigp>matrix(9,9,i,j,i==j)</lang>
map { [ (0) x $_, 1, (0) x ($n - $_) ] } 0..$n
 
=={{header|Perl}}==
<lang perl>sub identity_matrix {
my $n = shift;
map {
my $i = $_;
[ map { ($_ == $i) - 0 } 1 .. $n ]
} 1 .. $n;
}
 
@ARGV =for (<4, 5, 6>) unless @ARGV;{
say "\n$_:";
 
say join ' ', @$_ for identity_matrix $_;
for (@ARGV) {
}</syntaxhighlight>
my @id = identity_matrix $_;
print "$_:\n";
for (my $i=0; $i<@id; ++$i) {
print join ' ', @{$id[$i]}, "\n";
}
print "\n";
}
</lang>
{{out}}
<pre>4:
Line 1,068 ⟶ 2,989:
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1 </pre>
</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang perl6>sub identity-matrix($n) {
<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>
my @id;
<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>
for ^$n X ^$n -> $i, $j {
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
@id[$i][$j] = +($i == $j);
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
@id;
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
.say for identity-matrix(5);</lang>
<span style="color: #7060A8;">ppOpt</span><span style="color: #0000FF;">({</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</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;">3</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;">5</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>
<!--</syntaxhighlight>-->
{{out}}
<pre style="float:left">
<pre>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</pre>
<pre style="float:left">
On the other hand, this may be clearer and/or faster:
{{1,0,0,0,0},
<lang perl6>sub identity-matrix($n) {
{0,1,0,0,0},
my @id = [0 xx $n] xx $n;
{0,0,1,0,0},
@id[$_][$_] = 1 for ^$n;
{0,0,0,1,0},
@id;
{0,0,0,0,1}}
}</lang>
</pre>
<pre style="float:left">
{{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}}
</pre>
<pre>
{{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>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
function createMatrixidentity($sizelength) {
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1),
{
array_fill(0, $length, array_fill(0,$length, 0)));
$result = array();
 
for ($i = 0; $i < $size; $i++) {
$row = array_fill(0, $size, 0);
$row[$i] = 1;
$result[] = $row;
}
 
return $result;
}
function print_identity($identity) {
 
echo implode(PHP_EOL, array_map(function ($value) {return implode(' ', $value);}, $identity));
function printMatrix(array $matrix)
{
foreach ($matrix as $row) {
foreach ($row as $column) {
echo $column . " ";
}
echo PHP_EOL;
}
echo PHP_EOL;
}
print_identity(identity(10));
 
</syntaxhighlight>
printMatrix(createMatrix(5));
</lang>
{{out}}
<pre>
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
</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de identity (Size)
(let L (need Size (1) 0)
(make
(do Size
(link (copy (rot L))) ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (identity 3)
-> ((1 0 0) (0 1 0) (0 0 1))
 
Line 1,146 ⟶ 3,081:
(0 0 1 0 0)
(0 0 0 1 0)
(0 0 0 0 1)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
identity: procedure (A, n);
declare A(n,n) fixed controlled;
Line 1,156 ⟶ 3,091:
do i = 1 to n; A(i,i) = 1; end;
end identity;
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
<lang PostScript>
% n ident [identity-matrix]
% create an identity matrix of dimension n*n.
Line 1,176 ⟶ 3,111:
]
end } def
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function identity($n) {
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row}
}
function show($a) { $a | foreach{ "$_"} }
$array = identity 4
show $array
</syntaxhighlight>
<b>Output:</b>
<pre>
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
</pre>
<syntaxhighlight lang="powershell">
$array[0][0]
$array[0][1]
</syntaxhighlight>
<b>Output:</b>
<pre>
1
0
</pre>
 
 
 
=={{header|Prolog}}==
{{Works with|SWi-Prolog}}
<syntaxhighlight lang="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).
</syntaxhighlight>
 
{{out}}
<pre>?- 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 .
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="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)
Line 1,215 ⟶ 3,221:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
Sample output:
<pre> 1 0 0
0 1 0
Line 1,227 ⟶ 3,233:
 
=={{header|Python}}==
===Nested lists===
A simple solution, using nested lists.
A simple solution, using nested lists to represent the matrix.
<lang python>def identity(size):
<syntaxhighlight lang="python">def identity(size):
matrix = [[0] * size] * 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):
Line 1,237 ⟶ 3,245:
for elements in rows:
print elements,
print ""</langsyntaxhighlight>
 
===Nested maps and comprehensions===
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''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()</syntaxhighlight>
{{Out}}
<pre>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]</pre>
 
===Dict of points===
A dict of tuples of two ints (x, y) are used to represent the matrix.
<syntaxhighlight lang="python">>>> 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
>>> </syntaxhighlight>
 
===Numpy===
A solution using the numpy library
<langsyntaxhighlight lang="python">
np.mat(np.eye(size))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ [] swap times
[ 0 i^ of 1 join 0 i of
join nested join ] ] is identity ( n --> [ )
 
5 identity echo</syntaxhighlight>
{{out}}
<pre>
[ [ 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 ] ]
</pre>
 
=={{header|R}}==
When passed a single scalar argument, "<code>diag"</code> produces an identity matrix of size given by the scalar. For example:
 
<lang R>
<syntaxhighlight lang="rsplus">diag(3)</syntaxhighlight>
diag(3)
 
</lang>
produces:
 
<lang R>
<pre> [,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1</pre>
Or you can also use the method that is shown below
</lang>
<syntaxhighlight lang="rsplus">Identity_matrix=function(size){
x=matrix(0,size,size)
for (i in 1:size) {
x[i,i]=1
}
return(x)
}</syntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(identity-matrix 5)
</syntaxhighlight>
</lang>
{{out}}
Output:
<pre>
(array #[#[1 0 0 0 0]
Line 1,271 ⟶ 3,391:
#[0 0 0 1 0]
#[0 0 0 0 1]])
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-15}}
<syntaxhighlight lang="raku" line>sub identity-matrix($n) {
my @id;
for flat ^$n X ^$n -> $i, $j {
@id[$i][$j] = +($i == $j);
}
@id;
}
 
.say for identity-matrix(5);</syntaxhighlight>
{{out}}
<pre>[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]</pre>
On the other hand, this may be clearer and/or faster:
<syntaxhighlight lang="raku" line>sub identity-matrix($n) {
my @id = [0 xx $n] xx $n;
@id[$_][$_] = 1 for ^$n;
@id;
}</syntaxhighlight>
 
Here is yet an other way to do it:
<syntaxhighlight lang="raku" line>sub identity-matrix($n) {
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
}</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="rebol">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</syntaxhighlight>
{{out}}
<pre>
[[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]]
</pre>
 
=={{header|REXX}}==
===version 1===
The REXX language doesn't have matrixesmatrices as such, so the problem is largely how to display the "matrix".
<lang rexx>/*REXX program to create and display an identity matrix. */
call identity_matrix 4 /*build and display a 4x4 matrix.*/
call identity_matrix 5 /*build and display a 5x5 matrix.*/
exit /*stick a fork in it, we're done.*/
/*─────────────────────────────────────IDENTITY_MATRIX subroutine───────*/
identity_matrix: procedure; parse arg n; $=
 
The code to display the matrices was kept as a stand-alone general-purpose (square) matrix display
do r=1 for n /*build indentity matrix, by row,*/
<br>subroutine, &nbsp; which, in part, &nbsp; determines if the square matrix is indeed a square matrix based on the
do c=1 for n /* and by cow.*/
<br>number of elements given.
$=$ (r==c) /*append zero or one (if on diag)*/
end /*c*/
end /*r*/
 
It also finds the maximum widths of the integer and decimal fraction parts &nbsp; (if any) &nbsp; and uses those widths
call showMatrix 'identity matrix of size' n,$,n
<br>to align &nbsp; (right-justify according to the [possibly implied] decimal point) &nbsp; the columns of the square matrix.
return
/*─────────────────────────────────────TELL subroutine───&find the order*/
showMatrix: procedure; parse arg hdr,x,order,sep; if sep=='' then sep='═'
width=2 /*width of field to be used to display the elements*/
decPlaces=1 /*# decimal places to the right of decimal point. */
say; say center(hdr,max(length(hdr)+6,(width+1)*words(x)%order),sep); say
#=0
do row=1 for order; aLine=
do col=1 for order; #=#+1
aLine=aLine right(format(word(x,#),,decPlaces)/1, width)
end /*col*/ /*dividing by 1 normalizes the #.*/
say aLine
end /*row*/
return</lang>
'''output''' (using 4 and 5 for generating):
<pre style="overflow:scroll">
═══identity matrix of size 4═══
 
It also tries to display a centered (and easier to read) matrix, &nbsp; along with a title.
1 0 0 0
<syntaxhighlight lang="rexx">/*REXX program creates and displays any sized identity matrix (centered, with title).*/
0 1 0 0
do k=3 to 6 /* [↓] build and display a sq. matrix.*/
0 0 1 0
call ident_mat k /*build & display a KxK square matrix. */
0 0 0 1
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</syntaxhighlight>
{{out|output|text=&nbsp; when using the default sizes &nbsp; (3 ──► 6) &nbsp; for generating four matrices:}}
<pre>
────identity matrix of size 3────
 
1 0 0
═══identity matrix of size 5═══
0 1 0
0 0 1
 
────identity matrix of size 4────
1 0 0 0 0
 
0 1 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
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
</pre>
 
===version 2===
An alternative?!
<langsyntaxhighlight lang="rexx">
/* REXX ***************************************************************
* show identity matrix of size n
Line 1,341 ⟶ 3,535:
Say ol
End
</syntaxhighlight>
</lang>
{{out}}
Output
<pre>
Identity Matrix of size 3 (m.i.j IS the Matrix)
Line 1,349 ⟶ 3,543:
0 0 1
</pre>
This could be a 3-dimensional sparse matrix with one element set:
 
<syntaxhighlight lang="rexx">
This could be a 3-dimensional sparse matrix with one element set:
<lang rexx>
m.=0
m.0=1000 /* the matrix' size */
m.4.17.333='Walter'
</syntaxhighlight>
</lang>
 
=={{header|Ring}}==
<syntaxhighlight lang="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
</syntaxhighlight>
Output:
<pre>
10000
01000
00100
00010
00001
</pre>
 
Gui version
 
<syntaxhighlight lang="ring">
# 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
</syntaxhighlight>
Output image:
 
[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}}==
===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}}
end
Line 1,364 ⟶ 3,681:
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s}, ""
end</langsyntaxhighlight>
 
{{out}}
Line 1,389 ⟶ 3,706:
[0, 0, 0, 0, 0, 1]
</pre>
===Using Matrix===
<syntaxhighlight lang="ruby">
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]]
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">' formats array im() of size ims
for ims = 4 to 6
 
Line 1,410 ⟶ 3,733:
print "]"
next
next ims</langsyntaxhighlight>Output:
{{out}}
<pre>--- Size: 4 ---
[1, 0, 0, 0]
Line 1,431 ⟶ 3,755:
[0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 1]</pre>
 
=={{header|Rust}}==
 
Run with command-line containing the matrix size.
 
<syntaxhighlight lang="rust">
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!();
}
}
</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight 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"
 
printMatrix(identityMatrix(5))</langsyntaxhighlight>
{{out}}
Output:
<pre>[1, 0, 0, 0, 0]
[0, 1, 0, 0, 0]
Line 1,446 ⟶ 3,818:
=={{header|Scheme}}==
When representing a matrix as a collection of nested lists:
<langsyntaxhighlight lang="scheme">
(define (identity n)
(letrec
Line 1,462 ⟶ 3,834:
(cons (uvec i 0 '()) acc))))))
(idgen 0 '())))
</syntaxhighlight>
</lang>
Test program:
<langsyntaxhighlight lang="scheme">
(display (identity 4))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,473 ⟶ 3,845:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: matrix is array array integer;
Line 1,505 ⟶ 3,877:
begin
writeMat(identity(6));
end func;</langsyntaxhighlight>
 
{{out}}
Output:
<pre>
1 0 0 0 0 0
Line 1,515 ⟶ 3,887:
0 0 0 0 1 0
0 0 0 0 0 1
</pre>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="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
</syntaxhighlight>
Output for n 3
<pre>(1,0,0)
(0,1,0)
(0,0,1)</pre>
Output for n 17
<pre>(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)</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">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(' ')
}
}</syntaxhighlight>
 
{{out}}
<pre>
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
</pre>
 
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM, but for a larger matrix you'll want at least 2k.
<syntaxhighlight lang="zxbasic"> 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</syntaxhighlight>
{{in}}
<pre>10</pre>
{{out}}
<pre>1000000000
0100000000
0010000000
0001000000
0000100000
0000010000
0000001000
0000000100
0000000010
0000000001</pre>
 
=={{header|Smalltalk}}==
{{works with|Pharo Smalltalk}}
<syntaxhighlight lang="smalltalk">(Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString</syntaxhighlight>
{{Out}}
<pre>
'(1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1 )'
</pre>
 
=={{header|Sparkling}}==
<syntaxhighlight lang="sparkling">function unitMatrix(n) {
return map(range(n), function(k1, v1) {
return map(range(n), function(k2, v2) {
return v2 == v1 ? 1 : 0;
});
});
}</syntaxhighlight>
 
=={{header|Standard ML}}==
<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}}==
=== Stata matrix ===
<syntaxhighlight lang="stata">. mat a = I(3)
. mat list a
 
symmetric a[3,3]
c1 c2 c3
r1 1
r2 0 1
r3 0 0 1</syntaxhighlight>
 
=== Mata ===
<syntaxhighlight lang="stata">: I(3)
[symmetric]
1 2 3
+-------------+
1 | 1 |
2 | 0 1 |
3 | 0 0 1 |
+-------------+</syntaxhighlight>
 
=={{header|Swift}}==
 
{{trans|Elixir}}
 
<syntaxhighlight lang="swift">func identityMatrix(size: Int) -> [[Int]] {
return (0..<size).map({i in
return (0..<size).map({ $0 == i ? 1 : 0})
})
}
 
print(identityMatrix(size: 5))</syntaxhighlight>
 
{{out}}
 
<pre>[[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]]</pre>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
templates identityMatrix
def n: $;
[1..$n -> [1..~$ -> 0, 1, $~..$n -> 0]] !
end identityMatrix
 
def identity: 5 -> identityMatrix;
$identity... -> '|$(1);$(2..last)... -> ', $;';|
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
|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|
</pre>
 
=={{header|Tcl}}==
When representing a matrix as a collection of nested lists:
<langsyntaxhighlight lang="tcl">proc I {rank {zero 0.0} {one 1.0}} {
set m [lrepeat $rank [lrepeat $rank $zero]]
for {set i 0} {$i < $rank} {incr i} {
Line 1,525 ⟶ 4,098:
}
return $m
}</langsyntaxhighlight>
Or alternatively with the help of the tcllib package for rectangular data structures:
{{tcllib|struct::matrix}}
<langsyntaxhighlight lang="tcl">package require struct::matrix
 
proc I {rank {zero 0.0} {one 1.0}} {
Line 1,540 ⟶ 4,113:
}
return $m
}</langsyntaxhighlight>
Demonstrating the latter:
<langsyntaxhighlight lang="tcl">set m [I 5 0 1] ;# Integer 0/1 for clarity of presentation
puts [$m format 2string]</langsyntaxhighlight>
{{out}}
<pre>1 0 0 0 0
Line 1,551 ⟶ 4,124:
0 0 0 0 1</pre>
 
=={{header|UniconTypeScript}}==
<syntaxhighlight lang="typescript">
This code works for Icon and Unicon.
function identity(n) {
<lang unicon>link matrix
if (n < 1) return "Not defined";
procedure main(argv)
else if (n == 1) return 1;
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.")
else {
matrix1 := identity_matrix(argv[1], argv[1])
var idMatrix:number[][];
write_matrix(&output,matrix1)
for (var i: number = 0; i < n; i++) {
end
for (var j: number = 0; j < n; j++) {
</lang>
if (i != j) idMatrix[i][j] = 0;
else idMatrix[i][j] = 1;
}
}
return idMatrix;
}
}
</syntaxhighlight>
 
=={{header|Vala}}==
<syntaxhighlight lang="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;
}</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">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</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
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
</syntaxhighlight>
 
{{Out}}
<pre>
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
</pre>
 
 
'''Alternate version'''
 
<syntaxhighlight lang="vbscript">
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
</syntaxhighlight>
{{Out}}
<pre>
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
</pre>
 
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<syntaxhighlight lang="vb">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
</syntaxhighlight>
{{out}}
<pre>10000
01000
00100
00010
00001
 
1000000000
0100000000
0010000000
0001000000
0000100000
0000010000
0000001000
0000000100
0000000010
0000000001</pre>
 
=={{header|Wortel}}==
<syntaxhighlight lang="wortel">@let {
im ^(%^\@table ^(@+ =) @to)
 
!im 4
}</syntaxhighlight>
Returns:
<pre>[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]</pre>
 
=={{header|Wren}}==
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var numRows = 10 // say
Fmt.mprint(Matrix.identity(numRows), 2, 0)</syntaxhighlight>
 
{{out}}
<pre>
| 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|
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
def IntSize = 4; \number of bytes in an integer
int Matrix, Size, I, J;
Line 1,578 ⟶ 4,366:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Example output:
<pre>
Size: 5
Line 1,589 ⟶ 4,377:
0 0 0 0 1
</pre>
 
=={{header|zkl}}==
Using lists of lists:
<syntaxhighlight lang="zkl">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);</syntaxhighlight>
{{out}}
<pre>
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)
</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|Applesoft_BASIC}}
<syntaxhighlight lang="zxbasic">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</syntaxhighlight>
Anonymous user