Identity matrix: Difference between revisions

m
(add BQN)
imported>Arakov
 
(25 intermediate revisions by 20 users not shown)
Line 29:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F identity_matrix(size)
V matrix = [[0] * size] * size
L(i) 0 .< size
Line 36:
 
L(row) identity_matrix(3)
print(row)</langsyntaxhighlight>
 
{{out}}
Line 46:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Identity matrix 31/03/2017
INDENMAT CSECT
USING INDENMAT,R13 base register
Line 118:
A DS F a(n,n)
YREGS
END INDENMAT</langsyntaxhighlight>
{{out}}
<pre>
Line 131:
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}}==
Line 151 ⟶ 229:
'''Note:''' The generic vector and matrix code should be moved to a more generic page.
 
'''File: prelude/vector_base.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 183 ⟶ 261:
);
 
SKIP</langsyntaxhighlight>'''File: prelude/matrix_base.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
# Define some generic matrix initialisation and printing operations #
Line 234 ⟶ 312:
);
 
SKIP</langsyntaxhighlight>'''File: prelude/matrix_ident.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
PRIO IDENT = 9; # The same as I for COMPLex #
Line 244 ⟶ 322:
1 IDENT upb;
 
SKIP</langsyntaxhighlight>'''File: prelude/matrix.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 251 ⟶ 329:
PR READ "prelude/matrix_ident.a68" PR;
 
SKIP</langsyntaxhighlight>'''File: test/matrix_ident.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 259 ⟶ 337:
PR READ "prelude/matrix.a68" PR;
 
print(REPR IDENT 4)</langsyntaxhighlight>
{{out}}
<pre>
Line 269 ⟶ 347:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% set m to an identity matrix of size s %
procedure makeIdentity( real array m ( *, * )
Line 290 ⟶ 368:
end text
 
end.</langsyntaxhighlight>
 
=={{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}}==
Line 296 ⟶ 431:
 
For a square matrix of 3:
<langsyntaxhighlight lang="apl">
∘.=⍨⍳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
Line 312 ⟶ 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:
<langsyntaxhighlight lang="apl">
ID←∘.=⍨⍳
ID←⍳∘.=⍳
</syntaxhighlight>
</lang>
 
There is a more idomatic way however:
<langsyntaxhighlight lang="apl">
ID←{⍵ ⍵ ρ 1, ⍵ρ0}
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
 
<langsyntaxhighlight AppleScriptlang="applescript">--------------------- IDENTITY MATRIX ----------------------
 
-- identityMatrix :: Int -> [(0|1)]
Line 433 ⟶ 568:
set my text item delimiters to dlm
s
end unlines</langsyntaxhighlight>
{{Out}}
<pre>[1, 0, 0, 0, 0]
Line 440 ⟶ 575:
[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|Applesoft BASIC}}==
<lang ==={{header|Applesoft BASIC>}}===
<syntaxhighlight lang="applesoft basic">
100 INPUT "MATRIX SIZE:"; SIZE%
110 GOSUB 200"IDENTITYMATRIX
Line 458 ⟶ 653:
240 LET IM(I, I) = 1 : NEXT I
250 RETURN :IM
</syntaxhighlight>
</lang>
 
==={{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">
<lang ATS>
(* ****** ****** *)
//
Line 495 ⟶ 840:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">msgbox % Clipboard := I(6)
return
 
Line 513 ⟶ 858:
s .= " "
return Rtrim(r,"`n") "`n" s "--"
}</langsyntaxhighlight>
 
{{out}}
Line 528 ⟶ 873:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
Line 546 ⟶ 891:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5
<pre>
Line 557 ⟶ 902:
 
=={{header|Bash}}==
<syntaxhighlight lang="bash">
<lang Bash>
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
</syntaxhighlight>
</lang>
{{out}} for command: ./scriptname 5
<pre>
Line 571 ⟶ 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 587 ⟶ 932:
m(i%,i%) = 1
NEXT
ENDPROC</langsyntaxhighlight>
 
=={{header|Beads}}==
<langsyntaxhighlight lang="beads">beads 1 program 'Identity matrix'
 
var
Line 599 ⟶ 944:
loop from:1 to:n index:i
loop from:1 to:n index:j
id[i,j] = 1 if i == j else 0</langsyntaxhighlight>
 
{{out}}
Line 614 ⟶ 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 622 ⟶ 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:
 
<langsyntaxhighlight lang="burlesque">
blsq ) 6 ^^^^10\/**XXcy\/co.+sp
</syntaxhighlight>
</lang>
 
=={{header|BQN}}==
<syntaxhighlight lang="text">⍝ Using table
Eye ← =⌜˜∘↕
•Show Eye 3
Line 643 ⟶ 988:
⍝ Using reshape
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0}
Eye1 5</langsyntaxhighlight>
<syntaxhighlight lang="text">┌─
╵ 1 0 0
0 1 0
Line 656 ⟶ 1,001:
0 0 0 0 1
</syntaxhighlight>
</lang>
 
<code>Eye</code> generates an identity matrix using a table of equality for [0,n).
Line 665 ⟶ 1,010:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdlib.h>
#include <stdio.h>
Line 704 ⟶ 1,049:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Linq;
Line 743 ⟶ 1,088:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 756 ⟶ 1,101:
=={{header|C++}}==
{{libheader|STL}}
<langsyntaxhighlight lang="cpp">template<class T>
class matrix
{
Line 803 ⟶ 1,148:
return 0;
}
</syntaxhighlight>
</lang>
{{libheader|boost}}
<langsyntaxhighlight lang="cpp">
#include <boost/numeric/ublas/matrix.hpp>
 
Line 829 ⟶ 1,174:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 841 ⟶ 1,186:
 
=={{header|Clio}}==
<langsyntaxhighlight lang="clio">fn identity-matrix n:
[0:n] -> * fn i:
[0:n] -> * if = i: 1
else: 0
 
5 -> identity-matrix -> * print</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 852 ⟶ 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 861 ⟶ 1,206:
(vec
(reduce conj (drop i row ) (take i row)))))))
</syntaxhighlight>
</lang>
{{out}}
<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 879 ⟶ 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}}
Line 889 ⟶ 1,234:
#2A((1 0 0 0 0) (0 1 0 0 0) (0 0 1 0 0) (0 0 0 1 0) (0 0 0 0 1))
 
<langsyntaxhighlight 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>
</lang>
 
{{out}}
Line 904 ⟶ 1,249:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Algebras;
IMPORT StdLog,Strings;
Line 940 ⟶ 1,285:
END Do;
END Algebras.
</syntaxhighlight>
</lang>
Execute: ^Q Algebras.Do<br/>
{{out}}
Line 952 ⟶ 1,297:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.traits;
 
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
Line 981 ⟶ 1,326:
 
// auto id3 = matId!(const int)(2); // cant't compile
}</langsyntaxhighlight>
{{out}}
<pre>[[1, 0, 0, 0, 0],
Line 994 ⟶ 1,339:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program IdentityMatrix;
 
// Modified from the Pascal version
Line 1,018 ⟶ 1,363:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,028 ⟶ 1,373:
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">
<lang Eiffel>
class
APPLICATION
Line 1,092 ⟶ 1,450:
 
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,109 ⟶ 1,467:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import system'collections;
Line 1,116 ⟶ 1,474:
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()) }
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,133 ⟶ 1,491:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Matrix do
def identity(n) do
Enum.map(0..n-1, fn i ->
Line 1,141 ⟶ 1,499:
end
 
IO.inspect Matrix.identity(5)</langsyntaxhighlight>
 
{{out}}
Line 1,150 ⟶ 1,508:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%% Identity Matrix in Erlang for the Rosetta Code Wiki.
%% Implemented by Arjun Sunel
 
Line 1,160 ⟶ 1,518:
 
identity(Size) ->
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM IDENTITY
 
Line 1,184 ⟶ 1,542:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
function IdentityMatrix(n)
$ X:=zeros(n,n);
Line 1,196 ⟶ 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}}==
Line 1,218 ⟶ 1,576:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">IDMATRIX
=LAMBDA(n,
LET(
Line 1,230 ⟶ 1,588:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 1,328 ⟶ 1,686:
=={{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}}
<syntaxhighlight lang="fsharp">
<lang FSharp>
ident 10;;
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]
Line 1,345 ⟶ 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}}
<langsyntaxhighlight lang="factor">USING: math.matrices prettyprint ;
 
6 <identity-matrix> .</langsyntaxhighlight>
{{out}}
<pre>
Line 1,401 ⟶ 1,759:
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}}
<langsyntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED
 
: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix
Line 1,420 ⟶ 1,795:
6 6 float matrix a{{
a{{ 6 build-identity
6 6 a{{ }}fprint</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95}}
 
<langsyntaxhighlight lang="fortran">
program identitymatrix
 
Line 1,449 ⟶ 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.
<langsyntaxhighlight Fortranlang="fortran"> Program Identity
Integer N
Parameter (N = 666)
Line 1,461 ⟶ 1,836:
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i)
END</langsyntaxhighlight>
 
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:
<langsyntaxhighlight Fortranlang="fortran"> DO 1 I = 1,N
DO 1 J = 1,N
1 A(I,J) = (I/J)*(J/I)</langsyntaxhighlight>
Array assignment statements are also a feature of F90 and later.
 
Line 1,472 ⟶ 1,847:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim As Integer n
Line 1,503 ⟶ 1,878:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
Sample input/output
{{out}}
Line 1,517 ⟶ 1,892:
 
=={{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.
 
<langsyntaxhighlight lang="frink">n = parseInt[input["Enter matrix dimension as an integer: "]]
println[joinlnformatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</langsyntaxhighlight>
 
{{out}}
<pre>
Enter matrix dimension as an integer: 3
┌ ┐
[1, 0, 0]
│1 0 0│
[0, 1, 0]
│ │
[0, 0, 1]
│0 1 0│
│ │
│0 0 1│
└ ┘
</pre>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 )
 
println( identity(3) )</langsyntaxhighlight>
 
{{out}}
Line 1,543 ⟶ 1,922:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Identity_matrix}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Identity matrix 01.png]]
 
'''Test cases'''
 
[[File:Fōrmulæ - Identity matrix 02.png]]
 
[[File:Fōrmulæ - Identity matrix 03.png]]
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn IdentityMatrix( n as NSInteger ) as CFStringRef
NSInteger i, j
CFMutableArrayRef tempArr = fn MutableArrayWithCapacity( n )
CFMutableStringRef mutStr = fn MutableStringWithCapacity( 0 )
 
for i = 0 to n - 1
MutableArrayRemoveAllObjects( tempArr )
for j = 0 to n - 1
MutableArrayInsertObjectAtIndex( tempArr, @"0", j )
next
MutableArrayReplaceObjectAtIndex( tempArr, @"1", i )
MutableStringAppendString( mutStr, fn ArrayComponentsJoinedByString( tempArr, @" " ) )
MutableStringAppendString( mutStr, @"\n" )
next
end fn = fn StringWithString( mutStr )
 
NSLog( @"3:\n%@", fn IdentityMatrix( 3 ) )
NSLog( @"5:\n%@", fn IdentityMatrix( 5 ) )
NSLog( @"7:\n%@", fn IdentityMatrix( 7 ) )
NSLog( @"9:\n%@", fn IdentityMatrix( 9 ) )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
3:
1 0 0
0 1 0
0 0 1
 
5:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
 
7:
1 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 0
0 0 0 0 0 0 1
 
9:
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1
</pre>
 
In '''[https://formulae.org/?example=Identity_matrix this]''' page you can see the program(s) related to this task and their results.
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Built-in
IdentityMat(3);
 
# One can also specify the base ring
IdentityMat(3, Integers mod 10);</langsyntaxhighlight>
 
 
 
=={{header|Go}}==
===Library gonum/mat===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,576 ⟶ 2,026:
func main() {
fmt.Println(mat.Formatted(eye(3)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,586 ⟶ 2,036:
===Library go.matrix===
A somewhat earlier matrix library for Go.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,596 ⟶ 2,046:
func main() {
fmt.Println(mat.Eye(3))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,606 ⟶ 2,056:
===From scratch===
'''Simplest: ''' A matrix as a slice of slices, allocated separately.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,622 ⟶ 2,072:
}
return m
}</langsyntaxhighlight>
{{out}}
No special formatting method used.
Line 1,630 ⟶ 2,080:
 
'''2D, resliced: ''' Representation as a slice of slices still, but with all elements based on single underlying slice. Might save a little memory management, might have a little better locality.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,647 ⟶ 2,097:
}
return m
}</langsyntaxhighlight>
 
{{out}}
Line 1,653 ⟶ 2,103:
 
'''Flat: ''' Representation as a single flat slice. You just have to know to handle it as a square matrix. In many cases that's not a problem and the code is simpler this way. If you want to add a little bit of type checking, you can define a matrix type as shown here.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,686 ⟶ 2,136:
}
return m
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,697 ⟶ 2,147:
=={{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}}
Line 1,735 ⟶ 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 1,751 ⟶ 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:
 
<langsyntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]]
idMatrix n =
let xs = [1 .. n]
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</langsyntaxhighlight>
 
or reduce the number of terms a little to:
<langsyntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]]
idMatrix n =
let xs = [1 .. n]
Line 1,767 ⟶ 2,217:
 
main :: IO ()
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</langsyntaxhighlight>
{{Out}}
<pre>1 0 0 0 0
Line 1,778 ⟶ 2,228:
 
This code works for Icon and Unicon.
<langsyntaxhighlight lang="unicon">link matrix
procedure main(argv)
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.")
Line 1,784 ⟶ 2,234:
write_matrix(&output,matrix1)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,799 ⟶ 2,249:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Identity.bas"
110 INPUT PROMPT "Enter size of matrix: ":N
120 NUMERIC A(1 TO N,1 TO N)
Line 1,819 ⟶ 2,269:
280 PRINT
290 NEXT
300 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> = i. 4 NB. create an Identity matrix of size 4
1 0 0 0
0 1 0 0
Line 1,833 ⟶ 2,283:
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">public class PrintIdentityMatrix {
 
public static void main(String[] args) {
Line 1,848 ⟶ 2,298:
.forEach(System.out::println);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,861 ⟶ 2,311:
===ES5===
 
<langsyntaxhighlight Javascriptlang="javascript">function idMatrix(n) {
return Array.apply(null, new Array(n))
.map(function (x, i, xs) {
Line 1,868 ⟶ 2,318:
})
});
}</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// identityMatrix :: Int -> [[Int]]
Line 1,886 ⟶ 2,336:
.map(JSON.stringify)
.join('\n');
})();</langsyntaxhighlight>
{{Out}}
<pre>[1,0,0,0,0]
Line 1,896 ⟶ 2,346:
=={{header|jq}}==
===Construction===
<langsyntaxhighlight lang="jq">def identity(n):
[range(0;n) | 0] as $row
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</langsyntaxhighlight>
Example:
<syntaxhighlight lang ="jq">identity(4)</langsyntaxhighlight>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]]:
<langsyntaxhighlight lang="jq">def identity(n):
reduce range(0;n) as $i
(0 | matrix(n;n); .[$i][$i] = 1);
</syntaxhighlight>
</lang>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Identity matrix, in Jsish */
function identityMatrix(n) {
var mat = new Array(n).fill(0);
Line 1,943 ⟶ 2,393:
[ 0, 0, 0, 1 ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,953 ⟶ 2,403:
representing an identity matrix of any size,
boolean by default, that can be multiplied by a scalar
<langsyntaxhighlight Julialang="julia">using LinearAlgebra
unitfloat64matrix = 1.0I</langsyntaxhighlight>
 
UniformScaling object can be used as a function to construct a Diagonal
matrix of given size, that can be converted to a full matrix using <tt>collect</tt>
<langsyntaxhighlight Julialang="julia">using LinearAlgebra
diagI3 = 1.0I(3)
fullI3 = collect(diagI3)</langsyntaxhighlight>
 
The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are
 
<langsyntaxhighlight Julialang="julia">using LinearAlgebra
fullI3 = Matrix{Float64}(I, 3, 3)
fullI3 = Array{Float64}(I, 3, 3)
fullI3 = Array{Float64,2}(I, 3, 3)
fullI3 = zeros(3,3) + I</langsyntaxhighlight>
 
=={{header|K}}==
 
<langsyntaxhighlight Klang="k"> =4
(1 0 0 0
0 1 0 0
Line 1,983 ⟶ 2,433:
0 0 0 1 0
0 0 0 0 1)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 2,002 ⟶ 2,452:
else
println("Matrix is too big to display on 80 column console")
}</langsyntaxhighlight>
Sample input/output
{{out}}
Line 2,016 ⟶ 2,466:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def identity
{lambda {:n}
Line 2,031 ⟶ 2,481:
{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>
</lang>
 
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: identity-matrix
dup iota 'A set
 
Line 2,042 ⟶ 2,492:
;
 
5 identity-matrix .</langsyntaxhighlight>
{{out}}
<pre>[
Line 2,054 ⟶ 2,504:
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(defun identity
((`(,m ,n))
Line 2,063 ⟶ 2,513:
(defun identity (m n)
(lists:duplicate m (lists:duplicate n 1)))
</syntaxhighlight>
</lang>
 
From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix:
 
<langsyntaxhighlight lang="lisp">
> (identity 3)
((1 1 1) (1 1 1) (1 1 1))
Line 2,075 ⟶ 2,525:
((1 1 1) (1 1 1) (1 1 1))
 
</syntaxhighlight>
</lang>
 
=={{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 2,097 ⟶ 2,547:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>You: 0
Line 2,118 ⟶ 2,568:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function identity_matrix (size)
local m = {}
Line 2,136 ⟶ 2,586:
end
 
print_matrix(identity_matrix(5))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,147 ⟶ 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 2,156 ⟶ 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 2,167 ⟶ 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 2,178 ⟶ 2,628:
[ ]
[0 0 0 1]
</syntaxhighlight>
</lang>
 
=={{header|MathCortex}}==
<langsyntaxhighlight MathCortexlang="mathcortex">I = eye(10)</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang Mathematica="mathematica">IdentityMatrix[4]</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx ************************************************************
* show identity matrix of size n
* I consider m[i,j] to represent the matrix
Line 2,220 ⟶ 2,670:
Say ol
End
</syntaxhighlight>
</lang>
 
===Using Indexed String===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,260 ⟶ 2,710:
displayIdMatrix(createIdMatrix(n))
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class IdentityMatrix {
function : Matrix(n : Int) ~ Int[,] {
array := Int->New[n,n];
Line 2,302 ⟶ 2,752:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 2,308 ⟶ 2,758:
From the interactive loop (that we call the "toplevel"):
 
<langsyntaxhighlight lang="ocaml">$ ocaml
 
# let make_id_matrix n =
Line 2,324 ⟶ 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 2,340 ⟶ 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 2,347 ⟶ 2,797:
The '''eye''' function create the identity (I) matrix, e.g.:
 
<langsyntaxhighlight lang="octave">I = eye(10)</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (make-identity-matrix n)
(map (lambda (i)
Line 2,357 ⟶ 2,807:
 
(for-each print (make-identity-matrix 3))
(for-each print (make-identity-matrix 17))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,383 ⟶ 2,833:
=={{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 2,413 ⟶ 2,863:
say line
end i
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:20ex;overflow:scroll">
Line 2,432 ⟶ 2,882:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
Class SquareMatrix
'=================
Line 2,463 ⟶ 2,913:
'...
del M
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Built-in:
<syntaxhighlight lang ="parigp">matid(9)</langsyntaxhighlight>
 
Custom:
<langsyntaxhighlight lang="parigp">matrix(9,9,i,j,i==j)</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program IdentityMatrix(input, output);
 
var
Line 2,493 ⟶ 2,943:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,506 ⟶ 2,956:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
<lang perl>sub identity_matrix {
use warnings;
my $n = shift;
use feature 'say';
map {
 
my $i = $_;
sub identity_matrix {
[ map { ($_ == $i) - 0 } 1 .. $n ]
}my($n) 1= ..shift() $n- 1;
map { [ (0) x $_, 1, (0) x ($n - $_) ] } 0..$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 2,545 ⟶ 2,989:
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1 </pre>
</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 2,563 ⟶ 3,006:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="float:left">
Line 2,599 ⟶ 3,042:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
function identity($length) {
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1),
Line 2,608 ⟶ 3,051:
}
print_identity(identity(10));
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,624 ⟶ 3,067:
 
=={{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 2,638 ⟶ 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 2,648 ⟶ 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 2,668 ⟶ 3,111:
]
end } def
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function identity($n) {
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row}
Line 2,678 ⟶ 3,121:
$array = identity 4
show $array
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,686 ⟶ 3,129:
0 0 0 1
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
$array[0][0]
$array[0][1]
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,700 ⟶ 3,143:
=={{header|Prolog}}==
{{Works with|SWi-Prolog}}
<langsyntaxhighlight Prologlang="prolog">%rotates one list clockwise by one integer
rotate(Int,List,Rotated) :-
integer(Int),
Line 2,729 ⟶ 3,172:
idmatrix(5,I),
maplist(writeln,I).
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,742 ⟶ 3,185:
 
=={{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 2,778 ⟶ 3,221:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre> 1 0 0
Line 2,792 ⟶ 3,235:
===Nested lists===
A simple solution, using nested lists to represent the matrix.
<langsyntaxhighlight lang="python">def identity(size):
matrix = [[0]*size for i in range(size)]
#matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists
Line 2,802 ⟶ 3,245:
for elements in rows:
print elements,
print ""</langsyntaxhighlight>
 
===Nested maps and comprehensions===
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Identity matrices by maps and equivalent list comprehensions'''
 
import operator
Line 2,866 ⟶ 3,309:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>idMatrix:
Line 2,886 ⟶ 3,329:
===Dict of points===
A dict of tuples of two ints (x, y) are used to represent the matrix.
<langsyntaxhighlight lang="python">>>> def identity(size):
... return {(x, y):int(x == y) for x in range(size) for y in range(size)}
...
Line 2,896 ⟶ 3,339:
0 0 1 0
0 0 0 1
>>> </langsyntaxhighlight>
 
===Numpy===
A solution using the numpy library
<langsyntaxhighlight lang="python">
np.mat(np.eye(size))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
<langsyntaxhighlight lang="quackery">[ [] swap times
[ 0 i^ of 1 join 0 i of
join nested join ] ] is identity ( n --> [ )
 
5 identity echo</langsyntaxhighlight>
{{out}}
<pre>
Line 2,918 ⟶ 3,361:
When passed a single scalar argument, <code>diag</code> produces an identity matrix of size given by the scalar. For example:
 
<syntaxhighlight lang ="rsplus">diag(3)</langsyntaxhighlight>
 
produces:
Line 2,927 ⟶ 3,370:
[3,] 0 0 1</pre>
Or you can also use the method that is shown below
<langsyntaxhighlight lang="rsplus">Identity_matrix=function(size){
x=matrix(0,size,size)
for (i in 1:size) {
Line 2,933 ⟶ 3,376:
}
return(x)
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(identity-matrix 5)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,953 ⟶ 3,396:
(formerly Perl 6)
{{works with|rakudo|2015-09-15}}
<syntaxhighlight lang="raku" perl6line>sub identity-matrix($n) {
my @id;
for flat ^$n X ^$n -> $i, $j {
Line 2,961 ⟶ 3,404:
}
 
.say for identity-matrix(5);</langsyntaxhighlight>
{{out}}
<pre>[1 0 0 0 0]
Line 2,969 ⟶ 3,412:
[0 0 0 0 1]</pre>
On the other hand, this may be clearer and/or faster:
<syntaxhighlight lang="raku" perl6line>sub identity-matrix($n) {
my @id = [0 xx $n] xx $n;
@id[$_][$_] = 1 for ^$n;
@id;
}</langsyntaxhighlight>
 
Here is yet an other way to do it:
<syntaxhighlight lang="raku" perl6line>sub identity-matrix($n) {
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
}</langsyntaxhighlight>
 
=={{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}}==
Line 2,992 ⟶ 3,453:
 
It also tries to display a centered (and easier to read) matrix, &nbsp; along with a title.
<langsyntaxhighlight lang="rexx">/*REXX program creates and displays any sized identity matrix (centered, with title).*/
do k=3 to 6 /* [↓] build and display a sq. matrix.*/
call ident_mat k /*build & display a KxK square matrix. */
Line 3,021 ⟶ 3,482:
say _ /*display a single line of the matrix. */
end /*row*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default sizes &nbsp; (3 ──► 6) &nbsp; for generating four matrices:}}
<pre>
Line 3,057 ⟶ 3,518:
===version 2===
An alternative?!
<langsyntaxhighlight lang="rexx">
/* REXX ***************************************************************
* show identity matrix of size n
Line 3,074 ⟶ 3,535:
Say ol
End
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,083 ⟶ 3,544:
</pre>
This could be a 3-dimensional sparse matrix with one element set:
<langsyntaxhighlight lang="rexx">
m.=0
m.0=1000 /* the matrix' size */
m.4.17.333='Walter'
</syntaxhighlight>
</lang>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
size = 5
im = newlist(size, size)
Line 3,116 ⟶ 3,577:
next
return alist
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,124 ⟶ 3,585:
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===
<langsyntaxhighlight lang="ruby">def identity(size)
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}
end
Line 3,134 ⟶ 3,681:
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s}, ""
end</langsyntaxhighlight>
 
{{out}}
Line 3,160 ⟶ 3,707:
</pre>
===Using Matrix===
<langsyntaxhighlight lang="ruby">
2.1.1 :001 > require "'matrix"'
p Matrix.identity(5)
=> true
# => Matrix[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
2.1.1 :002 > Matrix.identity(5)
</syntaxhighlight>
=> Matrix[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">' formats array im() of size ims
for ims = 4 to 6
 
Line 3,187 ⟶ 3,733:
print "]"
next
next ims</langsyntaxhighlight>
{{out}}
<pre>--- Size: 4 ---
Line 3,214 ⟶ 3,760:
Run with command-line containing the matrix size.
 
<langsyntaxhighlight lang="rust">
extern crate num;
struct Matrix<T> {
Line 3,256 ⟶ 3,802:
}
}
</syntaxhighlight>
</lang>
 
=={{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}}
<pre>[1, 0, 0, 0, 0]
Line 3,272 ⟶ 3,818:
=={{header|Scheme}}==
When representing a matrix as a collection of nested lists:
<langsyntaxhighlight lang="scheme">
(define (identity n)
(letrec
Line 3,288 ⟶ 3,834:
(cons (uvec i 0 '()) acc))))))
(idgen 0 '())))
</syntaxhighlight>
</lang>
Test program:
<langsyntaxhighlight lang="scheme">
(display (identity 4))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,299 ⟶ 3,845:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: matrix is array array integer;
Line 3,331 ⟶ 3,877:
begin
writeMat(identity(6));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,344 ⟶ 3,890:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
set matrix to buildIdentityMatrix(3)
 
Line 3,373 ⟶ 3,919:
return matrixList
end buildIdentityMatrix
</syntaxhighlight>
</lang>
Output for n 3
<pre>(1,0,0)
Line 3,398 ⟶ 3,944:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func identity_matrix(n) {
n.of { |i|
n.of { |j|
Line 3,411 ⟶ 3,957:
say row.join(' ')
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,439 ⟶ 3,985:
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM, but for a larger matrix you'll want at least 2k.
<langsyntaxhighlight lang="zxbasic"> 10 INPUT S
20 DIM M(S,S)
30 FOR I=1 TO S
Line 3,450 ⟶ 3,996:
100 NEXT J
110 PRINT
120 NEXT I</langsyntaxhighlight>
{{in}}
<pre>10</pre>
Line 3,467 ⟶ 4,013:
=={{header|Smalltalk}}==
{{works with|Pharo Smalltalk}}
<langsyntaxhighlight lang="smalltalk">(Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString</langsyntaxhighlight>
{{Out}}
<pre>
Line 3,477 ⟶ 4,023:
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">function unitMatrix(n) {
return map(range(n), function(k1, v1) {
return map(range(n), function(k2, v2) {
Line 3,483 ⟶ 4,029:
});
});
}</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight Standardlang="standard MLml"> val eye= fn n => List.tabulate( n, fn i => List.tabulate( n, fn j=> if j=i then 1.0 else 0.0));</langsyntaxhighlight>
=={{header|Stata}}==
=== Stata matrix ===
<langsyntaxhighlight lang="stata">. mat a = I(3)
. mat list a
 
Line 3,496 ⟶ 4,042:
r1 1
r2 0 1
r3 0 0 1</langsyntaxhighlight>
 
=== Mata ===
<langsyntaxhighlight lang="stata">: I(3)
[symmetric]
1 2 3
Line 3,506 ⟶ 4,052:
2 | 0 1 |
3 | 0 0 1 |
+-------------+</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 3,512 ⟶ 4,058:
{{trans|Elixir}}
 
<langsyntaxhighlight lang="swift">func identityMatrix(size: Int) -> [[Int]] {
return (0..<size).map({i in
return (0..<size).map({ $0 == i ? 1 : 0})
Line 3,518 ⟶ 4,064:
}
 
print(identityMatrix(size: 5))</langsyntaxhighlight>
 
{{out}}
Line 3,525 ⟶ 4,071:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates identityMatrix
def n: $;
[1..$n -> \(def i: $; [1..~$n -> \(<=$i>0, 1, !$~..$n <-> 0 !\)] !\)] !
end identityMatrix
 
Line 3,534 ⟶ 4,080:
$identity... -> '|$(1);$(2..last)... -> ', $;';|
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,546 ⟶ 4,092:
=={{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 3,552 ⟶ 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 3,567 ⟶ 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 3,579 ⟶ 4,125:
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="typescript">
function identity(n) {
if (n < 1) return "Not defined";
Line 3,594 ⟶ 4,140:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">int main (string[] args) {
if (args.length < 2) {
print ("Please, input an integer > 0.\n");
Line 3,621 ⟶ 4,167:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Private Function Identity(n As Integer) As Variant
Dim I() As Integer
ReDim I(n - 1, n - 1)
Line 3,631 ⟶ 4,177:
Next j
Identity = I
End Function</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
build_matrix(7)
 
Line 3,664 ⟶ 4,210:
Next
End Sub
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,680 ⟶ 4,226:
'''Alternate version'''
 
<langsyntaxhighlight lang="vbscript">
n = 8
 
Line 3,696 ⟶ 4,242:
Identity = a
End Function
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,711 ⟶ 4,257:
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<langsyntaxhighlight lang="vb">Option Explicit
'------------
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte()
Line 3,749 ⟶ 4,295:
 
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>10000
Line 3,769 ⟶ 4,315:
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
im ^(%^\@table ^(@+ =) @to)
 
!im 4
}</langsyntaxhighlight>
Returns:
<pre>[[1 0 0 0]
Line 3,783 ⟶ 4,329:
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./matrix" for Matrix
import "./fmt" for Fmt
 
var numRows = 10 // say
Fmt.mprint(Matrix.identity(numRows), 2, 0)</langsyntaxhighlight>
 
{{out}}
Line 3,804 ⟶ 4,350:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
def IntSize = 4; \number of bytes in an integer
int Matrix, Size, I, J;
Line 3,820 ⟶ 4,366:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,834 ⟶ 4,380:
=={{header|zkl}}==
Using lists of lists:
<langsyntaxhighlight 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));
Line 3,840 ⟶ 4,386:
}
idMatrix(5).println();
idMatrix(5).pump(Console.println);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,853 ⟶ 4,399:
=={{header|ZX Spectrum Basic}}==
{{trans|Applesoft_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 INPUT "Matrix size: ";size
20 GO SUB 200: REM Identity matrix
30 FOR r=1 TO size
Line 3,868 ⟶ 4,414:
240 LET i(i,i)=1
250 NEXT i
260 RETURN</langsyntaxhighlight>
Anonymous user