Identity matrix: Difference between revisions

m
m (→‎{{header|Tailspin}}: syntax update)
imported>Arakov
 
(48 intermediate revisions by 31 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">-- ID MATRIX ------------------------------------------- IDENTITY MATRIX ----------------------
 
-- idMatrixidentityMatrix :: Int -> [(0|1)]
on idMatrixidentityMatrix(n)
set xs to enumFromTo(1, n)
script row
on |λ|(x)
script col
on |λ|(i)
if i = x then
Line 343 ⟶ 478:
end |λ|
end script
map(col, xs)
map(result, xs)
end |λ|
end script
map(row, xs)
end idMatrixidentityMatrix
 
 
-- TEST ------------------------------------------- TEST ---------------------------
on run
unlines(map(showList, ¬
idMatrix(5)
identityMatrix(5)))
end run
 
 
-- GENERIC FUNCTIONS ------------------------------------ GENERIC FUNCTIONS ---------------------
 
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if nm < mn then
set dlst to -1{}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
set d to 1{}
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
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]
Line 387 ⟶ 532:
end tell
end map
 
 
-- Lift 2nd class handler function into 1st class script wrapper
Line 398 ⟶ 544:
end script
end if
end mReturn</lang>
 
 
-- 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|Applesoft BASIC}}==
<lang ==={{header|Applesoft BASIC>}}===
<syntaxhighlight lang="applesoft basic">
100 INPUT "MATRIX SIZE:"; SIZE%
110 GOSUB 200"IDENTITYMATRIX
Line 423 ⟶ 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 460 ⟶ 840:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">msgbox % Clipboard := I(6)
return
 
Line 478 ⟶ 858:
s .= " "
return Rtrim(r,"`n") "`n" s "--"
}</langsyntaxhighlight>
 
{{out}}
Line 493 ⟶ 873:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
Line 511 ⟶ 891:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5
<pre>
Line 522 ⟶ 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 536 ⟶ 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 552 ⟶ 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 558 ⟶ 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 566 ⟶ 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
 
⍝ 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 589 ⟶ 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 601 ⟶ 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 607 ⟶ 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 620 ⟶ 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 671 ⟶ 1,148:
return 0;
}
</syntaxhighlight>
</lang>
{{libheader|boost}}
<langsyntaxhighlight lang="cpp">
#include <boost/numeric/ublas/matrix.hpp>
 
Line 697 ⟶ 1,174:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 706 ⟶ 1,183:
0 0 0 1 0
0 0 0 0 1
</pre>
 
=={{header|C sharp}}==
<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();
}
}
}
</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|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 768 ⟶ 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 777 ⟶ 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 795 ⟶ 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 805 ⟶ 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 820 ⟶ 1,249:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Algebras;
IMPORT StdLog,Strings;
Line 856 ⟶ 1,285:
END Do;
END Algebras.
</syntaxhighlight>
</lang>
Execute: ^Q Algebras.Do<br/>
{{out}}
Line 868 ⟶ 1,297:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.traits;
 
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
Line 897 ⟶ 1,326:
 
// auto id3 = matId!(const int)(2); // cant't compile
}</langsyntaxhighlight>
{{out}}
<pre>[[1, 0, 0, 0, 0],
Line 910 ⟶ 1,339:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program IdentityMatrix;
 
// Modified from the Pascal version
Line 934 ⟶ 1,363:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 944 ⟶ 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,008 ⟶ 1,450:
 
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,025 ⟶ 1,467:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import system'collections;
Line 1,032 ⟶ 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,049 ⟶ 1,491:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Matrix do
def identity(n) do
Enum.map(0..n-1, fn i ->
Line 1,057 ⟶ 1,499:
end
 
IO.inspect Matrix.identity(5)</langsyntaxhighlight>
 
{{out}}
Line 1,066 ⟶ 1,508:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">%% Identity Matrix in Erlang for the Rosetta Code Wiki.
%% Implemented by Arjun Sunel
 
Line 1,076 ⟶ 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,100 ⟶ 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,112 ⟶ 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}}
<syntaxhighlight lang="fsharp">
<lang FSharp>
ident 10;;
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]
Line 1,143 ⟶ 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}}
<lang factor>USE: math.matrices
<syntaxhighlight lang="factor">USING: math.matrices prettyprint ;
IN: scratchpad 6 identity-matrix .
 
6 <identity-matrix> .</syntaxhighlight>
{{out}}
<pre>
{
{ 1 0 0 0 0 0 }
Line 1,155 ⟶ 1,719:
{ 0 0 0 0 1 0 }
{ 0 0 0 0 0 1 }
}</langpre>
 
=={{header|FBSL}}==
Line 1,196 ⟶ 1,760:
</code></b></div>
 
=={{header|FōrmulæFermat}}==
<syntaxhighlight lang="fermat">
Func Identity(n)=Array id[n,n];[id]:=[1].
 
Identity(7)
In [http://wiki.formulae.org/Identity_matrix this] page you can see the solution of this task.
[id]
 
</syntaxhighlight>
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). 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 transportation effects more than visualization and edition.
{{out}}
 
<pre>
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
[[ 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,222 ⟶ 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,251 ⟶ 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,263 ⟶ 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,274 ⟶ 1,847:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim As Integer n
Line 1,305 ⟶ 1,878:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
Sample input/output
{{out}}
Line 1,316 ⟶ 1,889:
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}}==
<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,328 ⟶ 1,919:
((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}}==
<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,356 ⟶ 2,026:
func main() {
fmt.Println(mat.Formatted(eye(3)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,366 ⟶ 2,036:
===Library go.matrix===
A somewhat earlier matrix library for Go.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,376 ⟶ 2,046:
func main() {
fmt.Println(mat.Eye(3))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,386 ⟶ 2,056:
===From scratch===
'''Simplest: ''' A matrix as a slice of slices, allocated separately.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,402 ⟶ 2,072:
}
return m
}</langsyntaxhighlight>
{{out}}
No special formatting method used.
Line 1,410 ⟶ 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,427 ⟶ 2,097:
}
return m
}</langsyntaxhighlight>
 
{{out}}
Line 1,433 ⟶ 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,466 ⟶ 2,136:
}
return m
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,477 ⟶ 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,515 ⟶ 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,531 ⟶ 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,547 ⟶ 2,217:
 
main :: IO ()
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</langsyntaxhighlight>
{{Out}}
<pre>1 0 0 0 0
Line 1,558 ⟶ 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,564 ⟶ 2,234:
write_matrix(&output,matrix1)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,579 ⟶ 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,599 ⟶ 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,613 ⟶ 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,628 ⟶ 2,298:
.forEach(System.out::println);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,641 ⟶ 2,311:
===ES5===
 
<langsyntaxhighlight Javascriptlang="javascript">function idMatrix(n) {
return Array.apply(null, new Array(n))
.map(function (x, i, xs) {
Line 1,648 ⟶ 2,318:
})
});
}</langsyntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
 
// identityMatrix :: Int -> [[Int]]
<lang JavaScript>(() => {
const identityMatrix = n =>
 
// idMatrix :: Int -> [[0 | 1]]Array.from({
const idMatrix = n => Array.from({
length: n
}, (_, i) => Array.from({
Line 1,661 ⟶ 2,331:
}, (_, j) => i !== j ? 0 : 1));
 
// show :: a -> String
const show = JSON.stringify;
 
// ----------------------- TEST ------------------------
// TEST
return idMatrixidentityMatrix(5)
.map(showJSON.stringify)
.join('\n');
})();</langsyntaxhighlight>
 
{{Out}}
<pre>[1,0,0,0,0]
Line 1,679 ⟶ 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,726 ⟶ 2,393:
[ 0, 0, 0, 1 ]
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,733 ⟶ 2,400:
 
=={{header|Julia}}==
<tt>I</tt> is an object of type UniformScaling,
The <tt>I</tt> function takes an integer argument and returns a square identity matrix of that size.
representing an identity matrix of any size,
<lang Julia>using LinearAlgebra
boolean by default, that can be multiplied by a scalar
I(3)
<syntaxhighlight lang="julia">using LinearAlgebra
</lang>
unitfloat64matrix = 1.0I</syntaxhighlight>
This returns:
 
<pre>
UniformScaling object can be used as a function to construct a Diagonal
3x3 Float64 Array:
matrix of given size, that can be converted to a full matrix using <tt>collect</tt>
1.0 0.0 0.0
<syntaxhighlight lang="julia">using LinearAlgebra
0.0 1.0 0.0
0.0 0.0diagI3 = 1.00I(3)
fullI3 = collect(diagI3)</syntaxhighlight>
</pre>
 
The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are
 
<syntaxhighlight lang="julia">using LinearAlgebra
If you want to take the size from the commandline:
fullI3 = Matrix{Float64}(I, 3, 3)
<lang Julia>
fullI3 = Array{Float64}(I, 3, 3)
I(parse(Int, readline(stdin)))
fullI3 = Array{Float64,2}(I, 3, 3)
</lang>
fullI3 = zeros(3,3) + I</syntaxhighlight>
 
=={{header|K}}==
 
<langsyntaxhighlight Klang="k"> =4
(1 0 0 0
0 1 0 0
Line 1,763 ⟶ 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 1,782 ⟶ 2,452:
else
println("Matrix is too big to display on 80 column console")
}</langsyntaxhighlight>
Sample input/output
{{out}}
Line 1,795 ⟶ 2,465:
</pre>
 
=={{header|LSLLambdatalk}}==
<syntaxhighlight lang="scheme">
To test it yourself; rez a box on the ground, and add the following as a New Script.
{def identity
<lang LSL>default {
{lambda {:n}
state_entry() {
{A.new {S.map {{lambda {:n :i}
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
{A.new {S.map {{lambda {:i :j}
llOwnerSay("Please Enter a Dimension for an Identity Matrix.");
{if {= :i :j} then 1 else 0} } :i}
}
{S.serie 0 :n}}}} :n}
listen(integer iChannel, string sName, key kId, string sMessage) {
{S.serie 0 :n}} }}}
llOwnerSay("You entered "+sMessage+".");
-> identity
list lMatrix = [];
 
integer x = 0;
{identity 2}
integer n = (integer)sMessage;
-> [[1,0],[0,1]]
for(x=0 ; x<n*n ; x++) {
 
lMatrix += [(integer)(((x+1)%(n+1))==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]]
//llOwnerSay("["+llList2CSV(lMatrix)+"]");
</syntaxhighlight>
for(x=0 ; x<n ; x++) {
 
llOwnerSay("["+llList2CSV(llList2ListStrided(lMatrix, x*n, (x+1)*n-1, 1))+"]");
}
}
}</lang>
{{out}}
<pre>You: 0
Identity_Matrix: You entered 0.
You: 1
Identity_Matrix: You entered 1.
Identity_Matrix: [1]
You: 3
Identity_Matrix: You entered 3.
Identity_Matrix: [1, 0, 0]
Identity_Matrix: [0, 1, 0]
Identity_Matrix: [0, 0, 1]
You: 5
Identity_Matrix: You entered 5.
Identity_Matrix: [1, 0, 0, 0, 0]
Identity_Matrix: [0, 1, 0, 0, 0]
Identity_Matrix: [0, 0, 1, 0, 0]
Identity_Matrix: [0, 0, 0, 1, 0]
Identity_Matrix: [0, 0, 0, 0, 1]</pre>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: identity-matrix
dup iota 'A set
 
Line 1,843 ⟶ 2,492:
;
 
5 identity-matrix .</langsyntaxhighlight>
{{out}}
<pre>[
Line 1,855 ⟶ 2,504:
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">
(defun identity
((`(,m ,n))
Line 1,864 ⟶ 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 1,876 ⟶ 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.
<syntaxhighlight lang="lsl">default {
state_entry() {
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
llOwnerSay("Please Enter a Dimension for an Identity Matrix.");
}
listen(integer iChannel, string sName, key kId, string sMessage) {
llOwnerSay("You entered "+sMessage+".");
list lMatrix = [];
integer x = 0;
integer n = (integer)sMessage;
for(x=0 ; x<n*n ; x++) {
lMatrix += [(integer)(((x+1)%(n+1))==1)];
}
//llOwnerSay("["+llList2CSV(lMatrix)+"]");
for(x=0 ; x<n ; x++) {
llOwnerSay("["+llList2CSV(llList2ListStrided(lMatrix, x*n, (x+1)*n-1, 1))+"]");
}
}
}</syntaxhighlight>
{{out}}
<pre>You: 0
Identity_Matrix: You entered 0.
You: 1
Identity_Matrix: You entered 1.
Identity_Matrix: [1]
You: 3
Identity_Matrix: You entered 3.
Identity_Matrix: [1, 0, 0]
Identity_Matrix: [0, 1, 0]
Identity_Matrix: [0, 0, 1]
You: 5
Identity_Matrix: You entered 5.
Identity_Matrix: [1, 0, 0, 0, 0]
Identity_Matrix: [0, 1, 0, 0, 0]
Identity_Matrix: [0, 0, 1, 0, 0]
Identity_Matrix: [0, 0, 0, 1, 0]
Identity_Matrix: [0, 0, 0, 0, 1]</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function identity_matrix (size)
local m = {}
Line 1,897 ⟶ 2,586:
end
 
print_matrix(identity_matrix(5))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,908 ⟶ 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 1,917 ⟶ 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 1,928 ⟶ 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 1,939 ⟶ 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 1,981 ⟶ 2,670:
Say ol
End
</syntaxhighlight>
</lang>
 
===Using Indexed String===
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,021 ⟶ 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,063 ⟶ 2,752:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 2,069 ⟶ 2,758:
From the interactive loop (that we call the "toplevel"):
 
<langsyntaxhighlight lang="ocaml">$ ocaml
 
# let make_id_matrix n =
Line 2,085 ⟶ 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,101 ⟶ 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,108 ⟶ 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,118 ⟶ 2,807:
 
(for-each print (make-identity-matrix 3))
(for-each print (make-identity-matrix 17))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,144 ⟶ 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,174 ⟶ 2,863:
say line
end i
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:20ex;overflow:scroll">
Line 2,193 ⟶ 2,882:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
Class SquareMatrix
'=================
Line 2,224 ⟶ 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 2,247 ⟶ 2,943:
writeln;
end;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,259 ⟶ 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 2,306 ⟶ 2,989:
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1 </pre>
</pre>
 
=={{header|Perl 6}}==
{{works with|rakudo|2015-09-15}}
<lang perl6>sub identity-matrix($n) {
my @id;
for flat ^$n X ^$n -> $i, $j {
@id[$i][$j] = +($i == $j);
}
@id;
}
 
.say for identity-matrix(5);</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>
On the other hand, this may be clearer and/or faster:
<lang perl6>sub identity-matrix($n) {
my @id = [0 xx $n] xx $n;
@id[$_][$_] = 1 for ^$n;
@id;
}</lang>
 
Here is yet an other way to do it:
<lang perl6>sub identity-matrix($n) {
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
}</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function identity(integer 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>
sequence res = repeat(repeat(0,n),n)
<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 i=1 to n do
<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>
res[i][i] = 1
<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>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return res
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
ppOpt({pp_Nest,1})
<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>
pp(identity(3))
<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>
pp(identity(5))
<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>
pp(identity(7))
<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>
pp(identity(9))</lang>
<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">
Line 2,387 ⟶ 3,042:
 
=={{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 2,438 ⟶ 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,448 ⟶ 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,468 ⟶ 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,478 ⟶ 3,121:
$array = identity 4
show $array
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,486 ⟶ 3,129:
0 0 0 1
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
$array[0][0]
$array[0][1]
</syntaxhighlight>
</lang>
<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 2,533 ⟶ 3,221:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre> 1 0 0
Line 2,547 ⟶ 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,557 ⟶ 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,621 ⟶ 3,309:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>idMatrix:
Line 2,641 ⟶ 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,651 ⟶ 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}}==
<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:
 
<syntaxhighlight lang ="rsplus">diag(3)</langsyntaxhighlight>
 
produces:
Line 2,671 ⟶ 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,677 ⟶ 3,376:
}
return(x)
}</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
(identity-matrix 5)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,692 ⟶ 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>
 
Line 2,706 ⟶ 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 2,735 ⟶ 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 2,771 ⟶ 3,518:
===version 2===
An alternative?!
<langsyntaxhighlight lang="rexx">
/* REXX ***************************************************************
* show identity matrix of size n
Line 2,788 ⟶ 3,535:
Say ol
End
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,797 ⟶ 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 2,830 ⟶ 3,577:
next
return alist
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,838 ⟶ 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 2,848 ⟶ 3,681:
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s}, ""
end</langsyntaxhighlight>
 
{{out}}
Line 2,874 ⟶ 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 2,901 ⟶ 3,733:
print "]"
next
next ims</langsyntaxhighlight>
{{out}}
<pre>--- Size: 4 ---
Line 2,928 ⟶ 3,760:
Run with command-line containing the matrix size.
 
<langsyntaxhighlight lang="rust">
extern crate num;
struct Matrix<T> {
Line 2,970 ⟶ 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 2,986 ⟶ 3,818:
=={{header|Scheme}}==
When representing a matrix as a collection of nested lists:
<langsyntaxhighlight lang="scheme">
(define (identity n)
(letrec
Line 3,002 ⟶ 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,013 ⟶ 3,845:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: matrix is array array integer;
Line 3,045 ⟶ 3,877:
begin
writeMat(identity(6));
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,058 ⟶ 3,890:
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
set matrix to buildIdentityMatrix(3)
 
Line 3,087 ⟶ 3,919:
return matrixList
end buildIdentityMatrix
</syntaxhighlight>
</lang>
Output for n 3
<pre>(1,0,0)
Line 3,112 ⟶ 3,944:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func identity_matrix(n) {
n.of { |i|
n.of { |j|
Line 3,125 ⟶ 3,957:
say row.join(' ')
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,153 ⟶ 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,164 ⟶ 3,996:
100 NEXT J
110 PRINT
120 NEXT I</langsyntaxhighlight>
{{in}}
<pre>10</pre>
Line 3,181 ⟶ 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,191 ⟶ 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,197 ⟶ 4,029:
});
});
}</langsyntaxhighlight>
 
=={{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 ===
<langsyntaxhighlight lang="stata">. mat a = I(3)
. mat list a
 
Line 3,208 ⟶ 4,042:
r1 1
r2 0 1
r3 0 0 1</langsyntaxhighlight>
 
=== Mata ===
<langsyntaxhighlight lang="stata">: I(3)
[symmetric]
1 2 3
Line 3,218 ⟶ 4,052:
2 | 0 1 |
3 | 0 0 1 |
+-------------+</langsyntaxhighlight>
 
 
=={{header|Swift}}==
Line 3,225 ⟶ 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,231 ⟶ 4,064:
}
 
print(identityMatrix(size: 5))</langsyntaxhighlight>
 
{{out}}
Line 3,238 ⟶ 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,247 ⟶ 4,080:
$identity... -> '|$(1);$(2..last)... -> ', $;';|
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,259 ⟶ 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,265 ⟶ 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,280 ⟶ 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,292 ⟶ 4,125:
 
=={{header|TypeScript}}==
<langsyntaxhighlight lang="typescript">
function identity(n) {
if (n < 1) return "Not defined";
Line 3,307 ⟶ 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,334 ⟶ 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,344 ⟶ 4,177:
Next j
Identity = I
End Function</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
build_matrix(7)
 
Line 3,376 ⟶ 4,210:
Next
End Sub
</syntaxhighlight>
</lang>
 
{{Out}}
Line 3,392 ⟶ 4,226:
'''Alternate version'''
 
<langsyntaxhighlight lang="vbscript">
n = 8
 
Line 3,408 ⟶ 4,242:
Identity = a
End Function
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,423 ⟶ 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,461 ⟶ 4,295:
 
End Sub
</syntaxhighlight>
</lang>
{{out}}
<pre>10000
Line 3,481 ⟶ 4,315:
 
=={{header|Wortel}}==
<langsyntaxhighlight lang="wortel">@let {
im ^(%^\@table ^(@+ =) @to)
 
!im 4
}</langsyntaxhighlight>
Returns:
<pre>[[1 0 0 0]
Line 3,491 ⟶ 4,325:
[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 3,509 ⟶ 4,366:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,523 ⟶ 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,529 ⟶ 4,386:
}
idMatrix(5).println();
idMatrix(5).pump(Console.println);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,542 ⟶ 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,557 ⟶ 4,414:
240 LET i(i,i)=1
250 NEXT i
260 RETURN</langsyntaxhighlight>
Anonymous user