Identity matrix: Difference between revisions
Content added Content deleted
No edit summary |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 29: | Line 29: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F identity_matrix(size) |
||
V matrix = [[0] * size] * size |
V matrix = [[0] * size] * size |
||
L(i) 0 .< size |
L(i) 0 .< size |
||
Line 36: | Line 36: | ||
L(row) identity_matrix(3) |
L(row) identity_matrix(3) |
||
print(row)</ |
print(row)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 46: | Line 46: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* Identity matrix 31/03/2017 |
||
INDENMAT CSECT |
INDENMAT CSECT |
||
USING INDENMAT,R13 base register |
USING INDENMAT,R13 base register |
||
Line 118: | Line 118: | ||
A DS F a(n,n) |
A DS F a(n,n) |
||
YREGS |
YREGS |
||
END INDENMAT</ |
END INDENMAT</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 134: | Line 134: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC CreateIdentityMatrix(BYTE ARRAY mat,BYTE size) |
||
CARD pos |
CARD pos |
||
BYTE i,j |
BYTE i,j |
||
Line 191: | Line 191: | ||
LMARGIN=old ;restore left margin on the screen |
LMARGIN=old ;restore left margin on the screen |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Identity_matrix.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Identity_matrix.png Screenshot from Atari 8-bit computer] |
||
Line 213: | Line 213: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
When using floating point matrices in Ada 2005+ the function is defined as "Unit_Matrix" in Ada.Numerics.Generic_Real_Arrays. As a generic package it can work with user defined floating point types, or the predefined Short_Real_Arrays, Real_Arrays, and Long_Real_Arrays initializations. As seen below, the first indices of both dimensions can also be set since Ada array indices do not arbitrarily begin with a particular number. |
When using floating point matrices in Ada 2005+ the function is defined as "Unit_Matrix" in Ada.Numerics.Generic_Real_Arrays. As a generic package it can work with user defined floating point types, or the predefined Short_Real_Arrays, Real_Arrays, and Long_Real_Arrays initializations. As seen below, the first indices of both dimensions can also be set since Ada array indices do not arbitrarily begin with a particular number. |
||
< |
<syntaxhighlight lang="ada">-- As prototyped in the Generic_Real_Arrays specification: |
||
-- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix; |
-- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix; |
||
-- For the task: |
-- For the task: |
||
mat : Real_Matrix := Unit_Matrix(5);</ |
mat : Real_Matrix := Unit_Matrix(5);</syntaxhighlight> |
||
For prior versions of Ada, or non floating point types its back to basics: |
For prior versions of Ada, or non floating point types its back to basics: |
||
< |
<syntaxhighlight lang="ada">type Matrix is array(Positive Range <>, Positive Range <>) of Integer; |
||
mat : Matrix(1..5,1..5) := (others => (others => 0)); |
mat : Matrix(1..5,1..5) := (others => (others => 0)); |
||
-- then after the declarative section: |
-- then after the declarative section: |
||
for i in mat'Range(1) loop mat(i,i) := 1; end loop;</ |
for i in mat'Range(1) loop mat(i,i) := 1; end loop;</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 229: | Line 229: | ||
'''Note:''' The generic vector and matrix code should be moved to a more generic page. |
'''Note:''' The generic vector and matrix code should be moved to a more generic page. |
||
'''File: prelude/vector_base.a68'''< |
'''File: prelude/vector_base.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script # |
||
# -*- coding: utf-8 -*- # |
# -*- coding: utf-8 -*- # |
||
Line 261: | Line 261: | ||
); |
); |
||
SKIP</ |
SKIP</syntaxhighlight>'''File: prelude/matrix_base.a68'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- # |
||
# Define some generic matrix initialisation and printing operations # |
# Define some generic matrix initialisation and printing operations # |
||
Line 312: | Line 312: | ||
); |
); |
||
SKIP</ |
SKIP</syntaxhighlight>'''File: prelude/matrix_ident.a68'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- # |
||
PRIO IDENT = 9; # The same as I for COMPLex # |
PRIO IDENT = 9; # The same as I for COMPLex # |
||
Line 322: | Line 322: | ||
1 IDENT upb; |
1 IDENT upb; |
||
SKIP</ |
SKIP</syntaxhighlight>'''File: prelude/matrix.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script # |
||
# -*- coding: utf-8 -*- # |
# -*- coding: utf-8 -*- # |
||
Line 329: | Line 329: | ||
PR READ "prelude/matrix_ident.a68" PR; |
PR READ "prelude/matrix_ident.a68" PR; |
||
SKIP</ |
SKIP</syntaxhighlight>'''File: test/matrix_ident.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script # |
||
# -*- coding: utf-8 -*- # |
# -*- coding: utf-8 -*- # |
||
Line 337: | Line 337: | ||
PR READ "prelude/matrix.a68" PR; |
PR READ "prelude/matrix.a68" PR; |
||
print(REPR IDENT 4)</ |
print(REPR IDENT 4)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 347: | Line 347: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% set m to an identity matrix of size s % |
% set m to an identity matrix of size s % |
||
procedure makeIdentity( real array m ( *, * ) |
procedure makeIdentity( real array m ( *, * ) |
||
Line 368: | Line 368: | ||
end text |
end text |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|APL}}== |
=={{header|APL}}== |
||
Line 374: | Line 374: | ||
For a square matrix of 3: |
For a square matrix of 3: |
||
< |
<syntaxhighlight lang="apl"> |
||
∘.=⍨⍳3 |
∘.=⍨⍳3 |
||
1 0 0 |
1 0 0 |
||
0 1 0 |
0 1 0 |
||
0 0 1 |
0 0 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
For a function that makes an identity matrix: |
For a function that makes an identity matrix: |
||
< |
<syntaxhighlight lang="apl"> |
||
ID←{∘.=⍨⍳⍵} |
ID←{∘.=⍨⍳⍵} |
||
ID 5 |
ID 5 |
||
Line 390: | Line 390: | ||
0 0 0 1 0 |
0 0 0 1 0 |
||
0 0 0 0 1 |
0 0 0 0 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
An tacit function can be defined with one of the following equivalent lines: |
An tacit function can be defined with one of the following equivalent lines: |
||
< |
<syntaxhighlight lang="apl"> |
||
ID←∘.=⍨⍳ |
ID←∘.=⍨⍳ |
||
ID←⍳∘.=⍳ |
ID←⍳∘.=⍳ |
||
</syntaxhighlight> |
|||
</lang> |
|||
There is a more idomatic way however: |
There is a more idomatic way however: |
||
< |
<syntaxhighlight lang="apl"> |
||
ID←{⍵ ⍵ ρ 1, ⍵ρ0} |
ID←{⍵ ⍵ ρ 1, ⍵ρ0} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">--------------------- IDENTITY MATRIX ---------------------- |
||
-- identityMatrix :: Int -> [(0|1)] |
-- identityMatrix :: Int -> [(0|1)] |
||
Line 511: | Line 511: | ||
set my text item delimiters to dlm |
set my text item delimiters to dlm |
||
s |
s |
||
end unlines</ |
end unlines</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[1, 0, 0, 0, 0] |
<pre>[1, 0, 0, 0, 0] |
||
Line 520: | Line 520: | ||
---- |
---- |
||
===Simple alternative=== |
===Simple alternative=== |
||
< |
<syntaxhighlight lang="applescript">on indentityMatrix(n) |
||
set digits to {} |
set digits to {} |
||
set m to n - 1 |
set m to n - 1 |
||
Line 536: | Line 536: | ||
end indentityMatrix |
end indentityMatrix |
||
return indentityMatrix(5)</ |
return indentityMatrix(5)</syntaxhighlight> |
||
{{output}} |
{{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}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">identityM: function [n][ |
||
result: array.of: @[n n] 0 |
result: array.of: @[n n] 0 |
||
loop 0..dec n 'i -> result\[i]\[i]: 1 |
loop 0..dec n 'i -> result\[i]\[i]: 1 |
||
Line 553: | Line 553: | ||
loop identityM sz => print |
loop identityM sz => print |
||
print "" |
print "" |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 580: | Line 580: | ||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
<syntaxhighlight lang="applesoft basic"> |
|||
<lang Applesoft BASIC> |
|||
100 INPUT "MATRIX SIZE:"; SIZE% |
100 INPUT "MATRIX SIZE:"; SIZE% |
||
110 GOSUB 200"IDENTITYMATRIX |
110 GOSUB 200"IDENTITYMATRIX |
||
Line 596: | Line 596: | ||
240 LET IM(I, I) = 1 : NEXT I |
240 LET IM(I, I) = 1 : NEXT I |
||
250 RETURN :IM |
250 RETURN :IM |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
{{trans|Applesoft BASIC}} |
{{trans|Applesoft BASIC}} |
||
{{works with|Commodore BASIC|2.0}} |
{{works with|Commodore BASIC|2.0}} |
||
< |
<syntaxhighlight lang="gwbasic">100 INPUT "MATRIX SIZE:"; SIZE |
||
110 GOSUB 200: REM IDENTITYMATRIX |
110 GOSUB 200: REM IDENTITYMATRIX |
||
120 FOR R = 0 TO SIZE |
120 FOR R = 0 TO SIZE |
||
Line 617: | Line 617: | ||
240 IM(I, I) = 1 |
240 IM(I, I) = 1 |
||
250 NEXT I |
250 NEXT I |
||
260 RETURN</ |
260 RETURN</syntaxhighlight> |
||
==={{header|QBasic}}=== |
==={{header|QBasic}}=== |
||
Line 623: | Line 623: | ||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
{{trans|IS-BASIC}} |
{{trans|IS-BASIC}} |
||
< |
<syntaxhighlight lang="qbasic">SUB inicio(identity()) |
||
FOR i = LBOUND(identity,1) TO UBOUND(identity,1) |
FOR i = LBOUND(identity,1) TO UBOUND(identity,1) |
||
FOR j = LBOUND(identity,2) TO UBOUND(identity,2) |
FOR j = LBOUND(identity,2) TO UBOUND(identity,2) |
||
Line 648: | Line 648: | ||
CALL inicio(identity()) |
CALL inicio(identity()) |
||
CALL mostrar(identity())</ |
CALL mostrar(identity())</syntaxhighlight> |
||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="basic256">arraybase 1 |
||
do |
do |
||
input "Enter size of matrix: ", n |
input "Enter size of matrix: ", n |
||
Line 676: | Line 676: | ||
else |
else |
||
print "Matrix is too big to display on 80 column console" |
print "Matrix is too big to display on 80 column console" |
||
end if</ |
end if</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as FreeBASIC entry.</pre> |
<pre>Same as FreeBASIC entry.</pre> |
||
Line 682: | Line 682: | ||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
< |
<syntaxhighlight lang="freebasic">repeat |
||
input "Enter size of matrix: " n |
input "Enter size of matrix: " n |
||
until n > 0 |
until n > 0 |
||
Line 705: | Line 705: | ||
else |
else |
||
print "Matrix is too big to display on 80 column console" |
print "Matrix is too big to display on 80 column console" |
||
end if</ |
end if</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Same as FreeBASIC entry.</pre> |
<pre>Same as FreeBASIC entry.</pre> |
||
=={{header|ATS}}== |
=={{header|ATS}}== |
||
<syntaxhighlight lang="ats"> |
|||
<lang ATS> |
|||
(* ****** ****** *) |
(* ****** ****** *) |
||
// |
// |
||
Line 744: | Line 744: | ||
// |
// |
||
} (* end of [main0] *) |
} (* end of [main0] *) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">msgbox % Clipboard := I(6) |
||
return |
return |
||
Line 762: | Line 762: | ||
s .= " " |
s .= " " |
||
return Rtrim(r,"`n") "`n" s "--" |
return Rtrim(r,"`n") "`n" s "--" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 777: | Line 777: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f IDENTITY_MATRIX.AWK size |
# syntax: GAWK -f IDENTITY_MATRIX.AWK size |
||
BEGIN { |
BEGIN { |
||
Line 795: | Line 795: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5 |
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5 |
||
<pre> |
<pre> |
||
Line 806: | Line 806: | ||
=={{header|Bash}}== |
=={{header|Bash}}== |
||
<syntaxhighlight lang="bash"> |
|||
<lang Bash> |
|||
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done |
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} for command: ./scriptname 5 |
{{out}} for command: ./scriptname 5 |
||
<pre> |
<pre> |
||
Line 820: | Line 820: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> INPUT "Enter size of matrix: " size% |
||
PROCidentitymatrix(size%, im()) |
PROCidentitymatrix(size%, im()) |
||
FOR r% = 0 TO size%-1 |
FOR r% = 0 TO size%-1 |
||
Line 836: | Line 836: | ||
m(i%,i%) = 1 |
m(i%,i%) = 1 |
||
NEXT |
NEXT |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|Beads}}== |
=={{header|Beads}}== |
||
< |
<syntaxhighlight lang="beads">beads 1 program 'Identity matrix' |
||
var |
var |
||
Line 848: | Line 848: | ||
loop from:1 to:n index:i |
loop from:1 to:n index:i |
||
loop from:1 to:n index:j |
loop from:1 to:n index:j |
||
id[i,j] = 1 if i == j else 0</ |
id[i,j] = 1 if i == j else 0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 863: | Line 863: | ||
Neither very elegant nor short but it'll do |
Neither very elegant nor short but it'll do |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp |
blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp |
||
1 0 0 0 0 0 |
1 0 0 0 0 0 |
||
Line 871: | Line 871: | ||
0 0 0 0 1 0 |
0 0 0 0 1 0 |
||
0 0 0 0 0 1 |
0 0 0 0 0 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
The example above uses strings to generate the identity matrix. If you need a matrix with real numbers (Integers) then use: |
The example above uses strings to generate the identity matrix. If you need a matrix with real numbers (Integers) then use: |
||
< |
<syntaxhighlight lang="burlesque"> |
||
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e! |
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e! |
||
</syntaxhighlight> |
|||
</lang> |
|||
Shorter alternative: |
Shorter alternative: |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) 6 ^^^^10\/**XXcy\/co.+sp |
blsq ) 6 ^^^^10\/**XXcy\/co.+sp |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
<lang>⍝ Using table |
<syntaxhighlight lang="text">⍝ Using table |
||
Eye ← =⌜˜∘↕ |
Eye ← =⌜˜∘↕ |
||
•Show Eye 3 |
•Show Eye 3 |
||
Line 892: | Line 892: | ||
⍝ Using reshape |
⍝ Using reshape |
||
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0} |
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0} |
||
Eye1 5</ |
Eye1 5</syntaxhighlight> |
||
<lang>┌─ |
<syntaxhighlight lang="text">┌─ |
||
╵ 1 0 0 |
╵ 1 0 0 |
||
0 1 0 |
0 1 0 |
||
Line 905: | Line 905: | ||
0 0 0 0 1 |
0 0 0 0 1 |
||
┘ |
┘ |
||
</syntaxhighlight> |
|||
</lang> |
|||
<code>Eye</code> generates an identity matrix using a table of equality for [0,n). |
<code>Eye</code> generates an identity matrix using a table of equality for [0,n). |
||
Line 914: | Line 914: | ||
=={{header|C}}== |
=={{header|C}}== |
||
<syntaxhighlight lang="c"> |
|||
<lang C> |
|||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 953: | Line 953: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp"> |
||
using System; |
using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 992: | Line 992: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,005: | Line 1,005: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{libheader|STL}} |
{{libheader|STL}} |
||
< |
<syntaxhighlight lang="cpp">template<class T> |
||
class matrix |
class matrix |
||
{ |
{ |
||
Line 1,052: | Line 1,052: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{libheader|boost}} |
{{libheader|boost}} |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <boost/numeric/ublas/matrix.hpp> |
#include <boost/numeric/ublas/matrix.hpp> |
||
Line 1,078: | Line 1,078: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,090: | Line 1,090: | ||
=={{header|Clio}}== |
=={{header|Clio}}== |
||
< |
<syntaxhighlight lang="clio">fn identity-matrix n: |
||
[0:n] -> * fn i: |
[0:n] -> * fn i: |
||
[0:n] -> * if = i: 1 |
[0:n] -> * if = i: 1 |
||
else: 0 |
else: 0 |
||
5 -> identity-matrix -> * print</ |
5 -> identity-matrix -> * print</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 1,101: | Line 1,101: | ||
The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g. |
The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g. |
||
< |
<syntaxhighlight lang="clojure"> '( (0 1) (2 3) ) |
||
</syntaxhighlight> |
|||
</lang> |
|||
, then care to remove the vec function. |
, then care to remove the vec function. |
||
< |
<syntaxhighlight lang="clojure">(defn identity-matrix [n] |
||
(let [row (conj (repeat (dec n) 0) 1)] |
(let [row (conj (repeat (dec n) 0) 1)] |
||
(vec |
(vec |
||
Line 1,110: | Line 1,110: | ||
(vec |
(vec |
||
(reduce conj (drop i row ) (take i row))))))) |
(reduce conj (drop i row ) (take i row))))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="clojure">=> (identity-matrix 5) |
||
[[1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1]] |
[[1 0 0 0 0] [0 1 0 0 0] [0 0 1 0 0] [0 0 0 1 0] [0 0 0 0 1]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
The following is a more idomatic definition that utilizes infinite lists and cycling. |
The following is a more idomatic definition that utilizes infinite lists and cycling. |
||
< |
<syntaxhighlight lang="clojure"> |
||
(defn identity-matrix [n] |
(defn identity-matrix [n] |
||
(take n |
(take n |
||
(partition n (dec n) |
(partition n (dec n) |
||
(cycle (conj (repeat (dec n) 0) 1))))) |
(cycle (conj (repeat (dec n) 0) 1))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 1,128: | Line 1,128: | ||
Common Lisp provides multi-dimensional arrays. |
Common Lisp provides multi-dimensional arrays. |
||
< |
<syntaxhighlight lang="lisp">(defun make-identity-matrix (n) |
||
(let ((array (make-array (list n n) :initial-element 0))) |
(let ((array (make-array (list n n) :initial-element 0))) |
||
(loop for i below n do (setf (aref array i i) 1)) |
(loop for i below n do (setf (aref array i i) 1)) |
||
array)) |
array)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,138: | Line 1,138: | ||
#2A((1 0 0 0 0) (0 1 0 0 0) (0 0 1 0 0) (0 0 0 1 0) (0 0 0 0 1)) |
#2A((1 0 0 0 0) (0 1 0 0 0) (0 0 1 0 0) (0 0 0 1 0) (0 0 0 0 1)) |
||
< |
<syntaxhighlight lang="lisp">(defun identity-matrix (n) |
||
(loop for a from 1 to n |
(loop for a from 1 to n |
||
collect (loop for e from 1 to n |
collect (loop for e from 1 to n |
||
if (= a e) collect 1 |
if (= a e) collect 1 |
||
else collect 0))) |
else collect 0))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,153: | Line 1,153: | ||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE Algebras; |
MODULE Algebras; |
||
IMPORT StdLog,Strings; |
IMPORT StdLog,Strings; |
||
Line 1,189: | Line 1,189: | ||
END Do; |
END Do; |
||
END Algebras. |
END Algebras. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q Algebras.Do<br/> |
Execute: ^Q Algebras.Do<br/> |
||
{{out}} |
{{out}} |
||
Line 1,201: | Line 1,201: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.traits; |
||
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) { |
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) { |
||
Line 1,230: | Line 1,230: | ||
// auto id3 = matId!(const int)(2); // cant't compile |
// auto id3 = matId!(const int)(2); // cant't compile |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[[1, 0, 0, 0, 0], |
<pre>[[1, 0, 0, 0, 0], |
||
Line 1,243: | Line 1,243: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program IdentityMatrix; |
||
// Modified from the Pascal version |
// Modified from the Pascal version |
||
Line 1,267: | Line 1,267: | ||
writeln; |
writeln; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,279: | Line 1,279: | ||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
<syntaxhighlight lang="eiffel"> |
|||
<lang Eiffel> |
|||
class |
class |
||
APPLICATION |
APPLICATION |
||
Line 1,341: | Line 1,341: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,359: | Line 1,359: | ||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
import system'routines; |
import system'routines; |
||
import system'collections; |
import system'collections; |
||
Line 1,372: | Line 1,372: | ||
identity.forEach: |
identity.forEach: |
||
(row) { console.printLine(row.asEnumerable()) } |
(row) { console.printLine(row.asEnumerable()) } |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,382: | Line 1,382: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Matrix do |
||
def identity(n) do |
def identity(n) do |
||
Enum.map(0..n-1, fn i -> |
Enum.map(0..n-1, fn i -> |
||
Line 1,390: | Line 1,390: | ||
end |
end |
||
IO.inspect Matrix.identity(5)</ |
IO.inspect Matrix.identity(5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,399: | Line 1,399: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">%% Identity Matrix in Erlang for the Rosetta Code Wiki. |
||
%% Implemented by Arjun Sunel |
%% Implemented by Arjun Sunel |
||
Line 1,409: | Line 1,409: | ||
identity(Size) -> |
identity(Size) -> |
||
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</ |
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</syntaxhighlight> |
||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM IDENTITY |
PROGRAM IDENTITY |
||
Line 1,433: | Line 1,433: | ||
END FOR |
END FOR |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euler Math Toolbox}}== |
=={{header|Euler Math Toolbox}}== |
||
<syntaxhighlight lang="euler math toolbox"> |
|||
<lang Euler Math Toolbox> |
|||
function IdentityMatrix(n) |
function IdentityMatrix(n) |
||
$ X:=zeros(n,n); |
$ X:=zeros(n,n); |
||
Line 1,445: | Line 1,445: | ||
$ return X; |
$ return X; |
||
$endfunction |
$endfunction |
||
</syntaxhighlight> |
|||
</lang> |
|||
<syntaxhighlight lang="euler math toobox"> |
|||
<lang Euler Math Toobox> |
|||
>function IdentityMatrix (n:index) |
>function IdentityMatrix (n:index) |
||
$ return setdiag(zeros(n,n),0,1); |
$ return setdiag(zeros(n,n),0,1); |
||
$endfunction |
$endfunction |
||
</syntaxhighlight> |
|||
</lang> |
|||
<lang> |
<syntaxhighlight lang="text"> |
||
>id(5) |
>id(5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Excel}}== |
=={{header|Excel}}== |
||
Line 1,467: | Line 1,467: | ||
{{Works with|Office 365 betas 2021}} |
{{Works with|Office 365 betas 2021}} |
||
< |
<syntaxhighlight lang="lisp">IDMATRIX |
||
=LAMBDA(n, |
=LAMBDA(n, |
||
LET( |
LET( |
||
Line 1,479: | Line 1,479: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,577: | Line 1,577: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
Builds a 2D matrix with the given square size. |
Builds a 2D matrix with the given square size. |
||
<syntaxhighlight lang="fsharp"> |
|||
<lang FSharp> |
|||
let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0) |
let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<syntaxhighlight lang="fsharp"> |
|||
<lang FSharp> |
|||
ident 10;; |
ident 10;; |
||
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0] |
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0] |
||
Line 1,594: | Line 1,594: | ||
[0; 0; 0; 0; 0; 0; 0; 0; 1; 0] |
[0; 0; 0; 0; 0; 0; 0; 0; 1; 0] |
||
[0; 0; 0; 0; 0; 0; 0; 0; 0; 1]] |
[0; 0; 0; 0; 0; 0; 0; 0; 0; 1]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
{{works with|Factor|0.99 2020-07-03}} |
{{works with|Factor|0.99 2020-07-03}} |
||
< |
<syntaxhighlight lang="factor">USING: math.matrices prettyprint ; |
||
6 <identity-matrix> .</ |
6 <identity-matrix> .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,652: | Line 1,652: | ||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang="fermat"> |
||
Func Identity(n)=Array id[n,n];[id]:=[1]. |
Func Identity(n)=Array id[n,n];[id]:=[1]. |
||
Identity(7) |
Identity(7) |
||
[id] |
[id] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,671: | Line 1,671: | ||
{{libheader|Forth Scientific Library}} |
{{libheader|Forth Scientific Library}} |
||
{{works with|gforth|0.7.9_20170308}} |
{{works with|gforth|0.7.9_20170308}} |
||
< |
<syntaxhighlight lang="forth">S" fsl-util.fs" REQUIRED |
||
: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix |
: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix |
||
Line 1,686: | Line 1,686: | ||
6 6 float matrix a{{ |
6 6 float matrix a{{ |
||
a{{ 6 build-identity |
a{{ 6 build-identity |
||
6 6 a{{ }}fprint</ |
6 6 a{{ }}fprint</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|95}} |
{{works with|Fortran|95}} |
||
< |
<syntaxhighlight lang="fortran"> |
||
program identitymatrix |
program identitymatrix |
||
Line 1,715: | Line 1,715: | ||
end program identitymatrix |
end program identitymatrix |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Notorious trick=== |
===Notorious trick=== |
||
The objective is to do the assignment in one fell swoop, rather than separately setting the 0 values and the 1 values. It works because, with integer arithmetic, the only way that both i/j and j/i are one is when they are equal - thus one on the diagonal elements, and zero elsewhere because either i < j so that i/j = 0, or i > j so that j/i = 0. While this means two divides and a multiply per element instead of simply transferring a constant, the constraint on speed is likely to be the limited bandwidth from cpu to memory. The expression's code would surely fit in the cpu's internal memory, and registers would be used for the variables. |
The objective is to do the assignment in one fell swoop, rather than separately setting the 0 values and the 1 values. It works because, with integer arithmetic, the only way that both i/j and j/i are one is when they are equal - thus one on the diagonal elements, and zero elsewhere because either i < j so that i/j = 0, or i > j so that j/i = 0. While this means two divides and a multiply per element instead of simply transferring a constant, the constraint on speed is likely to be the limited bandwidth from cpu to memory. The expression's code would surely fit in the cpu's internal memory, and registers would be used for the variables. |
||
< |
<syntaxhighlight lang="fortran"> Program Identity |
||
Integer N |
Integer N |
||
Parameter (N = 666) |
Parameter (N = 666) |
||
Line 1,727: | Line 1,727: | ||
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i) |
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i) |
||
END</ |
END</syntaxhighlight> |
||
The <code>ForAll</code> statement is a feature of F90, and carries the implication that the assignments may be done in any order, even "simultaneously" (as with multiple cpus), plus that all RHS values are calculated before any LHS part receives a value - not relevant here since the RHS makes no reference to items altered in the LHS. Earlier Fortran compilers lack this statement and so one must use explicit DO-loops: |
The <code>ForAll</code> statement is a feature of F90, and carries the implication that the assignments may be done in any order, even "simultaneously" (as with multiple cpus), plus that all RHS values are calculated before any LHS part receives a value - not relevant here since the RHS makes no reference to items altered in the LHS. Earlier Fortran compilers lack this statement and so one must use explicit DO-loops: |
||
< |
<syntaxhighlight lang="fortran"> DO 1 I = 1,N |
||
DO 1 J = 1,N |
DO 1 J = 1,N |
||
1 A(I,J) = (I/J)*(J/I)</ |
1 A(I,J) = (I/J)*(J/I)</syntaxhighlight> |
||
Array assignment statements are also a feature of F90 and later. |
Array assignment statements are also a feature of F90 and later. |
||
Line 1,738: | Line 1,738: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Dim As Integer n |
Dim As Integer n |
||
Line 1,769: | Line 1,769: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
Sample input/output |
Sample input/output |
||
{{out}} |
{{out}} |
||
Line 1,785: | Line 1,785: | ||
This does not use the Matrix.frink library, which has methods to create an identity matrix, but shows how to build a "raw" identity matrix as a two-dimensional array, and shows how to nicely format it using built-in routines. |
This does not use the Matrix.frink library, which has methods to create an identity matrix, but shows how to build a "raw" identity matrix as a two-dimensional array, and shows how to nicely format it using built-in routines. |
||
< |
<syntaxhighlight lang="frink">n = parseInt[input["Enter matrix dimension as an integer: "]] |
||
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</ |
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,801: | Line 1,801: | ||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
< |
<syntaxhighlight lang="funl">def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 ) |
||
println( identity(3) )</ |
println( identity(3) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,821: | Line 1,821: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic"> |
||
include "NSLog.incl" |
include "NSLog.incl" |
||
Line 1,846: | Line 1,846: | ||
HandleEvents |
HandleEvents |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{output}} |
{{output}} |
||
<pre> |
<pre> |
||
Line 1,884: | Line 1,884: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># Built-in |
||
IdentityMat(3); |
IdentityMat(3); |
||
# One can also specify the base ring |
# One can also specify the base ring |
||
IdentityMat(3, Integers mod 10);</ |
IdentityMat(3, Integers mod 10);</syntaxhighlight> |
||
Line 1,894: | Line 1,894: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
===Library gonum/mat=== |
===Library gonum/mat=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,912: | Line 1,912: | ||
func main() { |
func main() { |
||
fmt.Println(mat.Formatted(eye(3))) |
fmt.Println(mat.Formatted(eye(3))) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,922: | Line 1,922: | ||
===Library go.matrix=== |
===Library go.matrix=== |
||
A somewhat earlier matrix library for Go. |
A somewhat earlier matrix library for Go. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,932: | Line 1,932: | ||
func main() { |
func main() { |
||
fmt.Println(mat.Eye(3)) |
fmt.Println(mat.Eye(3)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,942: | Line 1,942: | ||
===From scratch=== |
===From scratch=== |
||
'''Simplest: ''' A matrix as a slice of slices, allocated separately. |
'''Simplest: ''' A matrix as a slice of slices, allocated separately. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,958: | Line 1,958: | ||
} |
} |
||
return m |
return m |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
No special formatting method used. |
No special formatting method used. |
||
Line 1,966: | Line 1,966: | ||
'''2D, resliced: ''' Representation as a slice of slices still, but with all elements based on single underlying slice. Might save a little memory management, might have a little better locality. |
'''2D, resliced: ''' Representation as a slice of slices still, but with all elements based on single underlying slice. Might save a little memory management, might have a little better locality. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,983: | Line 1,983: | ||
} |
} |
||
return m |
return m |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,989: | Line 1,989: | ||
'''Flat: ''' Representation as a single flat slice. You just have to know to handle it as a square matrix. In many cases that's not a problem and the code is simpler this way. If you want to add a little bit of type checking, you can define a matrix type as shown here. |
'''Flat: ''' Representation as a single flat slice. You just have to know to handle it as a square matrix. In many cases that's not a problem and the code is simpler this way. If you want to add a little bit of type checking, you can define a matrix type as shown here. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,022: | Line 2,022: | ||
} |
} |
||
return m |
return m |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,033: | Line 2,033: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def makeIdentityMatrix = { n -> |
||
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } } |
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } } |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">(2..6).each { order -> |
||
def iMatrix = makeIdentityMatrix(order) |
def iMatrix = makeIdentityMatrix(order) |
||
iMatrix.each { println it } |
iMatrix.each { println it } |
||
println() |
println() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,071: | Line 2,071: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]</syntaxhighlight> |
||
And a function to show matrix pretty: |
And a function to show matrix pretty: |
||
< |
<syntaxhighlight lang="haskell">showMat :: [[Int]] -> String |
||
showMat = unlines . map (unwords . map show)</ |
showMat = unlines . map (unwords . map show)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="haskell">*Main> putStr $ showMat $ matId 9 |
||
1 0 0 0 0 0 0 0 0 |
1 0 0 0 0 0 0 0 0 |
||
0 1 0 0 0 0 0 0 0 |
0 1 0 0 0 0 0 0 0 |
||
Line 2,087: | Line 2,087: | ||
0 0 0 0 0 0 0 1 0 |
0 0 0 0 0 0 0 1 0 |
||
0 0 0 0 0 0 0 0 1 |
0 0 0 0 0 0 0 0 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
We could alternatively bypassing the syntactic sugaring of list comprehension notation, and use a bind function directly: |
We could alternatively bypassing the syntactic sugaring of list comprehension notation, and use a bind function directly: |
||
< |
<syntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]] |
||
idMatrix n = |
idMatrix n = |
||
let xs = [1 .. n] |
let xs = [1 .. n] |
||
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</ |
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</syntaxhighlight> |
||
or reduce the number of terms a little to: |
or reduce the number of terms a little to: |
||
< |
<syntaxhighlight lang="haskell">idMatrix :: Int -> [[Int]] |
||
idMatrix n = |
idMatrix n = |
||
let xs = [1 .. n] |
let xs = [1 .. n] |
||
Line 2,103: | Line 2,103: | ||
main :: IO () |
main :: IO () |
||
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</ |
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1 0 0 0 0 |
<pre>1 0 0 0 0 |
||
Line 2,114: | Line 2,114: | ||
This code works for Icon and Unicon. |
This code works for Icon and Unicon. |
||
< |
<syntaxhighlight lang="unicon">link matrix |
||
procedure main(argv) |
procedure main(argv) |
||
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.") |
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.") |
||
Line 2,120: | Line 2,120: | ||
write_matrix(&output,matrix1) |
write_matrix(&output,matrix1) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,135: | Line 2,135: | ||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "Identity.bas" |
||
110 INPUT PROMPT "Enter size of matrix: ":N |
110 INPUT PROMPT "Enter size of matrix: ":N |
||
120 NUMERIC A(1 TO N,1 TO N) |
120 NUMERIC A(1 TO N,1 TO N) |
||
Line 2,155: | Line 2,155: | ||
280 PRINT |
280 PRINT |
||
290 NEXT |
290 NEXT |
||
300 END DEF</ |
300 END DEF</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> = i. 4 NB. create an Identity matrix of size 4 |
||
1 0 0 0 |
1 0 0 0 |
||
0 1 0 0 |
0 1 0 0 |
||
Line 2,169: | Line 2,169: | ||
0 0 1 0 0 |
0 0 1 0 0 |
||
0 0 0 1 0 |
0 0 0 1 0 |
||
0 0 0 0 1</ |
0 0 0 0 1</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public class PrintIdentityMatrix { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
Line 2,184: | Line 2,184: | ||
.forEach(System.out::println); |
.forEach(System.out::println); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,197: | Line 2,197: | ||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang="javascript">function idMatrix(n) { |
||
return Array.apply(null, new Array(n)) |
return Array.apply(null, new Array(n)) |
||
.map(function (x, i, xs) { |
.map(function (x, i, xs) { |
||
Line 2,204: | Line 2,204: | ||
}) |
}) |
||
}); |
}); |
||
}</ |
}</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
// identityMatrix :: Int -> [[Int]] |
// identityMatrix :: Int -> [[Int]] |
||
Line 2,222: | Line 2,222: | ||
.map(JSON.stringify) |
.map(JSON.stringify) |
||
.join('\n'); |
.join('\n'); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[1,0,0,0,0] |
<pre>[1,0,0,0,0] |
||
Line 2,232: | Line 2,232: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
===Construction=== |
===Construction=== |
||
< |
<syntaxhighlight lang="jq">def identity(n): |
||
[range(0;n) | 0] as $row |
[range(0;n) | 0] as $row |
||
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</ |
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</syntaxhighlight> |
||
Example: |
Example: |
||
<lang |
<syntaxhighlight lang="jq">identity(4)</syntaxhighlight>produces: |
||
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]] |
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]] |
||
===Using matrix/2=== |
===Using matrix/2=== |
||
Using the definition of matrix/2 at [[Create_a_two-dimensional_array_at_runtime#jq]]: |
Using the definition of matrix/2 at [[Create_a_two-dimensional_array_at_runtime#jq]]: |
||
< |
<syntaxhighlight lang="jq">def identity(n): |
||
reduce range(0;n) as $i |
reduce range(0;n) as $i |
||
(0 | matrix(n;n); .[$i][$i] = 1); |
(0 | matrix(n;n); .[$i][$i] = 1); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Jsish}}== |
=={{header|Jsish}}== |
||
< |
<syntaxhighlight lang="javascript">/* Identity matrix, in Jsish */ |
||
function identityMatrix(n) { |
function identityMatrix(n) { |
||
var mat = new Array(n).fill(0); |
var mat = new Array(n).fill(0); |
||
Line 2,279: | Line 2,279: | ||
[ 0, 0, 0, 1 ] |
[ 0, 0, 0, 1 ] |
||
=!EXPECTEND!= |
=!EXPECTEND!= |
||
*/</ |
*/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,289: | Line 2,289: | ||
representing an identity matrix of any size, |
representing an identity matrix of any size, |
||
boolean by default, that can be multiplied by a scalar |
boolean by default, that can be multiplied by a scalar |
||
< |
<syntaxhighlight lang="julia">using LinearAlgebra |
||
unitfloat64matrix = 1.0I</ |
unitfloat64matrix = 1.0I</syntaxhighlight> |
||
UniformScaling object can be used as a function to construct a Diagonal |
UniformScaling object can be used as a function to construct a Diagonal |
||
matrix of given size, that can be converted to a full matrix using <tt>collect</tt> |
matrix of given size, that can be converted to a full matrix using <tt>collect</tt> |
||
< |
<syntaxhighlight lang="julia">using LinearAlgebra |
||
diagI3 = 1.0I(3) |
diagI3 = 1.0I(3) |
||
fullI3 = collect(diagI3)</ |
fullI3 = collect(diagI3)</syntaxhighlight> |
||
The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are |
The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are |
||
< |
<syntaxhighlight lang="julia">using LinearAlgebra |
||
fullI3 = Matrix{Float64}(I, 3, 3) |
fullI3 = Matrix{Float64}(I, 3, 3) |
||
fullI3 = Array{Float64}(I, 3, 3) |
fullI3 = Array{Float64}(I, 3, 3) |
||
fullI3 = Array{Float64,2}(I, 3, 3) |
fullI3 = Array{Float64,2}(I, 3, 3) |
||
fullI3 = zeros(3,3) + I</ |
fullI3 = zeros(3,3) + I</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> =4 |
||
(1 0 0 0 |
(1 0 0 0 |
||
0 1 0 0 |
0 1 0 0 |
||
Line 2,319: | Line 2,319: | ||
0 0 0 1 0 |
0 0 0 1 0 |
||
0 0 0 0 1) |
0 0 0 0 1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 2,338: | Line 2,338: | ||
else |
else |
||
println("Matrix is too big to display on 80 column console") |
println("Matrix is too big to display on 80 column console") |
||
}</ |
}</syntaxhighlight> |
||
Sample input/output |
Sample input/output |
||
{{out}} |
{{out}} |
||
Line 2,352: | Line 2,352: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
{def identity |
{def identity |
||
{lambda {:n} |
{lambda {:n} |
||
Line 2,367: | Line 2,367: | ||
{identity 5} |
{identity 5} |
||
-> [[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]] |
-> [[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">: identity-matrix |
||
dup iota 'A set |
dup iota 'A set |
||
Line 2,378: | Line 2,378: | ||
; |
; |
||
5 identity-matrix .</ |
5 identity-matrix .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[ |
<pre>[ |
||
Line 2,390: | Line 2,390: | ||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun identity |
(defun identity |
||
((`(,m ,n)) |
((`(,m ,n)) |
||
Line 2,399: | Line 2,399: | ||
(defun identity (m n) |
(defun identity (m n) |
||
(lists:duplicate m (lists:duplicate n 1))) |
(lists:duplicate m (lists:duplicate n 1))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix: |
From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (identity 3) |
> (identity 3) |
||
((1 1 1) (1 1 1) (1 1 1)) |
((1 1 1) (1 1 1) (1 1 1)) |
||
Line 2,411: | Line 2,411: | ||
((1 1 1) (1 1 1) (1 1 1)) |
((1 1 1) (1 1 1) (1 1 1)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|LSL}}== |
=={{header|LSL}}== |
||
To test it yourself; rez a box on the ground, and add the following as a New Script. |
To test it yourself; rez a box on the ground, and add the following as a New Script. |
||
< |
<syntaxhighlight lang="lsl">default { |
||
state_entry() { |
state_entry() { |
||
llListen(PUBLIC_CHANNEL, "", llGetOwner(), ""); |
llListen(PUBLIC_CHANNEL, "", llGetOwner(), ""); |
||
Line 2,433: | Line 2,433: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>You: 0 |
<pre>You: 0 |
||
Line 2,454: | Line 2,454: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
function identity_matrix (size) |
function identity_matrix (size) |
||
local m = {} |
local m = {} |
||
Line 2,472: | Line 2,472: | ||
end |
end |
||
print_matrix(identity_matrix(5))</ |
print_matrix(identity_matrix(5))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,483: | Line 2,483: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
One of a number of ways to do this: |
One of a number of ways to do this: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> LinearAlgebra:-IdentityMatrix( 4 ); |
> LinearAlgebra:-IdentityMatrix( 4 ); |
||
[1 0 0 0] |
[1 0 0 0] |
||
Line 2,492: | Line 2,492: | ||
[ ] |
[ ] |
||
[0 0 0 1] |
[0 0 0 1] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Here, for instance, is another, in which the entries are (4-byte) floats. |
Here, for instance, is another, in which the entries are (4-byte) floats. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> Matrix( 4, shape = scalar[1], datatype = float[4] ); |
> Matrix( 4, shape = scalar[1], datatype = float[4] ); |
||
[1. 0. 0. 0.] |
[1. 0. 0. 0.] |
||
Line 2,503: | Line 2,503: | ||
[ ] |
[ ] |
||
[0. 0. 0. 1.] |
[0. 0. 0. 1.] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Yet another, with 2-byte integer entries: |
Yet another, with 2-byte integer entries: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> Matrix( 4, shape = identity, datatype = integer[ 2 ] ); |
> Matrix( 4, shape = identity, datatype = integer[ 2 ] ); |
||
[1 0 0 0] |
[1 0 0 0] |
||
Line 2,514: | Line 2,514: | ||
[ ] |
[ ] |
||
[0 0 0 1] |
[0 0 0 1] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MathCortex}}== |
=={{header|MathCortex}}== |
||
< |
<syntaxhighlight lang="mathcortex">I = eye(10)</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
<lang |
<syntaxhighlight lang="mathematica">IdentityMatrix[4]</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
The '''eye''' function create the identity (I) matrix, e.g.: |
The '''eye''' function create the identity (I) matrix, e.g.: |
||
< |
<syntaxhighlight lang="matlab">I = eye(10)</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">ident(4); |
||
/* matrix([1, 0, 0, 0], |
/* matrix([1, 0, 0, 0], |
||
[0, 1, 0, 0], |
[0, 1, 0, 0], |
||
[0, 0, 1, 0], |
[0, 0, 1, 0], |
||
[0, 0, 0, 1]) */</ |
[0, 0, 0, 1]) */</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
===Using int Array=== |
===Using int Array=== |
||
{{trans|REXX}} |
{{trans|REXX}} |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx ************************************************************ |
||
* show identity matrix of size n |
* show identity matrix of size n |
||
* I consider m[i,j] to represent the matrix |
* I consider m[i,j] to represent the matrix |
||
Line 2,556: | Line 2,556: | ||
Say ol |
Say ol |
||
End |
End |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using Indexed String=== |
===Using Indexed String=== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 2,596: | Line 2,596: | ||
displayIdMatrix(createIdMatrix(n)) |
displayIdMatrix(createIdMatrix(n)) |
||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc identityMatrix(n: Positive): auto = |
||
result = newSeq[seq[int]](n) |
result = newSeq[seq[int]](n) |
||
for i in 0 ..< result.len: |
for i in 0 ..< result.len: |
||
result[i] = newSeq[int](n) |
result[i] = newSeq[int](n) |
||
result[i][i] = 1</ |
result[i][i] = 1</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">class IdentityMatrix { |
||
function : Matrix(n : Int) ~ Int[,] { |
function : Matrix(n : Int) ~ Int[,] { |
||
array := Int->New[n,n]; |
array := Int->New[n,n]; |
||
Line 2,638: | Line 2,638: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 2,644: | Line 2,644: | ||
From the interactive loop (that we call the "toplevel"): |
From the interactive loop (that we call the "toplevel"): |
||
< |
<syntaxhighlight lang="ocaml">$ ocaml |
||
# let make_id_matrix n = |
# let make_id_matrix n = |
||
Line 2,660: | Line 2,660: | ||
[|0.; 1.; 0.; 0.|]; |
[|0.; 1.; 0.; 0.|]; |
||
[|0.; 0.; 1.; 0.|]; |
[|0.; 0.; 1.; 0.|]; |
||
[|0.; 0.; 0.; 1.|] |]</ |
[|0.; 0.; 0.; 1.|] |]</syntaxhighlight> |
||
another way: |
another way: |
||
< |
<syntaxhighlight lang="ocaml"># let make_id_matrix n = |
||
Array.init n (fun i -> |
Array.init n (fun i -> |
||
Array.init n (fun j -> |
Array.init n (fun j -> |
||
Line 2,676: | Line 2,676: | ||
[|0.; 1.; 0.; 0.|]; |
[|0.; 1.; 0.; 0.|]; |
||
[|0.; 0.; 1.; 0.|]; |
[|0.; 0.; 1.; 0.|]; |
||
[|0.; 0.; 0.; 1.|] |]</ |
[|0.; 0.; 0.; 1.|] |]</syntaxhighlight> |
||
When we write a function in the toplevel, it returns us its signature (the prototype), and when we write a variable (or a function call), it returns its type and its value. |
When we write a function in the toplevel, it returns us its signature (the prototype), and when we write a variable (or a function call), it returns its type and its value. |
||
Line 2,683: | Line 2,683: | ||
The '''eye''' function create the identity (I) matrix, e.g.: |
The '''eye''' function create the identity (I) matrix, e.g.: |
||
< |
<syntaxhighlight lang="octave">I = eye(10)</syntaxhighlight> |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (make-identity-matrix n) |
(define (make-identity-matrix n) |
||
(map (lambda (i) |
(map (lambda (i) |
||
Line 2,693: | Line 2,693: | ||
(for-each print (make-identity-matrix 3)) |
(for-each print (make-identity-matrix 3)) |
||
(for-each print (make-identity-matrix 17))</ |
(for-each print (make-identity-matrix 17))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,719: | Line 2,719: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays. |
ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
say "a 3x3 identity matrix" |
say "a 3x3 identity matrix" |
||
say |
say |
||
Line 2,749: | Line 2,749: | ||
say line |
say line |
||
end i |
end i |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="height:20ex;overflow:scroll"> |
<pre style="height:20ex;overflow:scroll"> |
||
Line 2,768: | Line 2,768: | ||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
Class SquareMatrix |
Class SquareMatrix |
||
'================= |
'================= |
||
Line 2,799: | Line 2,799: | ||
'... |
'... |
||
del M |
del M |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Built-in: |
Built-in: |
||
<lang |
<syntaxhighlight lang="parigp">matid(9)</syntaxhighlight> |
||
Custom: |
Custom: |
||
< |
<syntaxhighlight lang="parigp">matrix(9,9,i,j,i==j)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">program IdentityMatrix(input, output); |
||
var |
var |
||
Line 2,829: | Line 2,829: | ||
writeln; |
writeln; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,842: | Line 2,842: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use warnings; |
use warnings; |
||
use feature 'say'; |
use feature 'say'; |
||
Line 2,854: | Line 2,854: | ||
say "\n$_:"; |
say "\n$_:"; |
||
say join ' ', @$_ for identity_matrix $_; |
say join ' ', @$_ for identity_matrix $_; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>4: |
<pre>4: |
||
Line 2,878: | Line 2,878: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> |
||
Line 2,892: | Line 2,892: | ||
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">))</span> |
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">))</span> |
||
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span> |
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre style="float:left"> |
<pre style="float:left"> |
||
Line 2,928: | Line 2,928: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"> |
||
function identity($length) { |
function identity($length) { |
||
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1), |
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1), |
||
Line 2,937: | Line 2,937: | ||
} |
} |
||
print_identity(identity(10)); |
print_identity(identity(10)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,953: | Line 2,953: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de identity (Size) |
||
(let L (need Size (1) 0) |
(let L (need Size (1) 0) |
||
(make |
(make |
||
(do Size |
(do Size |
||
(link (copy (rot L))) ) ) ) )</ |
(link (copy (rot L))) ) ) ) )</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="picolisp">: (identity 3) |
||
-> ((1 0 0) (0 1 0) (0 0 1)) |
-> ((1 0 0) (0 1 0) (0 0 1)) |
||
Line 2,967: | Line 2,967: | ||
(0 0 1 0 0) |
(0 0 1 0 0) |
||
(0 0 0 1 0) |
(0 0 0 1 0) |
||
(0 0 0 0 1)</ |
(0 0 0 0 1)</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
identity: procedure (A, n); |
identity: procedure (A, n); |
||
declare A(n,n) fixed controlled; |
declare A(n,n) fixed controlled; |
||
Line 2,977: | Line 2,977: | ||
do i = 1 to n; A(i,i) = 1; end; |
do i = 1 to n; A(i,i) = 1; end; |
||
end identity; |
end identity; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
<syntaxhighlight lang="postscript"> |
|||
<lang PostScript> |
|||
% n ident [identity-matrix] |
% n ident [identity-matrix] |
||
% create an identity matrix of dimension n*n. |
% create an identity matrix of dimension n*n. |
||
Line 2,997: | Line 2,997: | ||
] |
] |
||
end } def |
end } def |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function identity($n) { |
function identity($n) { |
||
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row} |
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row} |
||
Line 3,007: | Line 3,007: | ||
$array = identity 4 |
$array = identity 4 |
||
show $array |
show $array |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
<pre> |
<pre> |
||
Line 3,015: | Line 3,015: | ||
0 0 0 1 |
0 0 0 1 |
||
</pre> |
</pre> |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
$array[0][0] |
$array[0][0] |
||
$array[0][1] |
$array[0][1] |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
<pre> |
<pre> |
||
Line 3,029: | Line 3,029: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
{{Works with|SWi-Prolog}} |
{{Works with|SWi-Prolog}} |
||
< |
<syntaxhighlight lang="prolog">%rotates one list clockwise by one integer |
||
rotate(Int,List,Rotated) :- |
rotate(Int,List,Rotated) :- |
||
integer(Int), |
integer(Int), |
||
Line 3,058: | Line 3,058: | ||
idmatrix(5,I), |
idmatrix(5,I), |
||
maplist(writeln,I). |
maplist(writeln,I). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,071: | Line 3,071: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">>Procedure identityMatrix(Array i(2), size) ;valid only for size >= 0 |
||
;formats array i() as an identity matrix of size x size |
;formats array i() as an identity matrix of size x size |
||
Dim i(size - 1, size - 1) |
Dim i(size - 1, size - 1) |
||
Line 3,107: | Line 3,107: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 0 0 |
<pre> 1 0 0 |
||
Line 3,121: | Line 3,121: | ||
===Nested lists=== |
===Nested lists=== |
||
A simple solution, using nested lists to represent the matrix. |
A simple solution, using nested lists to represent the matrix. |
||
< |
<syntaxhighlight lang="python">def identity(size): |
||
matrix = [[0]*size for i in range(size)] |
matrix = [[0]*size for i in range(size)] |
||
#matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists |
#matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists |
||
Line 3,131: | Line 3,131: | ||
for elements in rows: |
for elements in rows: |
||
print elements, |
print elements, |
||
print ""</ |
print ""</syntaxhighlight> |
||
===Nested maps and comprehensions=== |
===Nested maps and comprehensions=== |
||
{{Works with|Python|3.7}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Identity matrices by maps and equivalent list comprehensions''' |
||
import operator |
import operator |
||
Line 3,195: | Line 3,195: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>idMatrix: |
<pre>idMatrix: |
||
Line 3,215: | Line 3,215: | ||
===Dict of points=== |
===Dict of points=== |
||
A dict of tuples of two ints (x, y) are used to represent the matrix. |
A dict of tuples of two ints (x, y) are used to represent the matrix. |
||
< |
<syntaxhighlight lang="python">>>> def identity(size): |
||
... return {(x, y):int(x == y) for x in range(size) for y in range(size)} |
... return {(x, y):int(x == y) for x in range(size) for y in range(size)} |
||
... |
... |
||
Line 3,225: | Line 3,225: | ||
0 0 1 0 |
0 0 1 0 |
||
0 0 0 1 |
0 0 0 1 |
||
>>> </ |
>>> </syntaxhighlight> |
||
===Numpy=== |
===Numpy=== |
||
A solution using the numpy library |
A solution using the numpy library |
||
< |
<syntaxhighlight lang="python"> |
||
np.mat(np.eye(size)) |
np.mat(np.eye(size)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery">[ [] swap times |
||
[ 0 i^ of 1 join 0 i of |
[ 0 i^ of 1 join 0 i of |
||
join nested join ] ] is identity ( n --> [ ) |
join nested join ] ] is identity ( n --> [ ) |
||
5 identity echo</ |
5 identity echo</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,247: | Line 3,247: | ||
When passed a single scalar argument, <code>diag</code> produces an identity matrix of size given by the scalar. For example: |
When passed a single scalar argument, <code>diag</code> produces an identity matrix of size given by the scalar. For example: |
||
<lang |
<syntaxhighlight lang="rsplus">diag(3)</syntaxhighlight> |
||
produces: |
produces: |
||
Line 3,256: | Line 3,256: | ||
[3,] 0 0 1</pre> |
[3,] 0 0 1</pre> |
||
Or you can also use the method that is shown below |
Or you can also use the method that is shown below |
||
< |
<syntaxhighlight lang="rsplus">Identity_matrix=function(size){ |
||
x=matrix(0,size,size) |
x=matrix(0,size,size) |
||
for (i in 1:size) { |
for (i in 1:size) { |
||
Line 3,262: | Line 3,262: | ||
} |
} |
||
return(x) |
return(x) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(require math) |
(require math) |
||
(identity-matrix 5) |
(identity-matrix 5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,282: | Line 3,282: | ||
(formerly Perl 6) |
(formerly Perl 6) |
||
{{works with|rakudo|2015-09-15}} |
{{works with|rakudo|2015-09-15}} |
||
<lang |
<syntaxhighlight lang="raku" line>sub identity-matrix($n) { |
||
my @id; |
my @id; |
||
for flat ^$n X ^$n -> $i, $j { |
for flat ^$n X ^$n -> $i, $j { |
||
Line 3,290: | Line 3,290: | ||
} |
} |
||
.say for identity-matrix(5);</ |
.say for identity-matrix(5);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1 0 0 0 0] |
<pre>[1 0 0 0 0] |
||
Line 3,298: | Line 3,298: | ||
[0 0 0 0 1]</pre> |
[0 0 0 0 1]</pre> |
||
On the other hand, this may be clearer and/or faster: |
On the other hand, this may be clearer and/or faster: |
||
<lang |
<syntaxhighlight lang="raku" line>sub identity-matrix($n) { |
||
my @id = [0 xx $n] xx $n; |
my @id = [0 xx $n] xx $n; |
||
@id[$_][$_] = 1 for ^$n; |
@id[$_][$_] = 1 for ^$n; |
||
@id; |
@id; |
||
}</ |
}</syntaxhighlight> |
||
Here is yet an other way to do it: |
Here is yet an other way to do it: |
||
<lang |
<syntaxhighlight lang="raku" line>sub identity-matrix($n) { |
||
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1] |
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="rebol">Red[] |
||
identity-matrix: function [size][ |
identity-matrix: function [size][ |
||
Line 3,321: | Line 3,321: | ||
] |
] |
||
probe identity-matrix 5</ |
probe identity-matrix 5</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,339: | Line 3,339: | ||
It also tries to display a centered (and easier to read) matrix, along with a title. |
It also tries to display a centered (and easier to read) matrix, along with a title. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program creates and displays any sized identity matrix (centered, with title).*/ |
||
do k=3 to 6 /* [↓] build and display a sq. matrix.*/ |
do k=3 to 6 /* [↓] build and display a sq. matrix.*/ |
||
call ident_mat k /*build & display a KxK square matrix. */ |
call ident_mat k /*build & display a KxK square matrix. */ |
||
Line 3,368: | Line 3,368: | ||
say _ /*display a single line of the matrix. */ |
say _ /*display a single line of the matrix. */ |
||
end /*row*/ |
end /*row*/ |
||
return</ |
return</syntaxhighlight> |
||
{{out|output|text= when using the default sizes (3 ──► 6) for generating four matrices:}} |
{{out|output|text= when using the default sizes (3 ──► 6) for generating four matrices:}} |
||
<pre> |
<pre> |
||
Line 3,404: | Line 3,404: | ||
===version 2=== |
===version 2=== |
||
An alternative?! |
An alternative?! |
||
< |
<syntaxhighlight lang="rexx"> |
||
/* REXX *************************************************************** |
/* REXX *************************************************************** |
||
* show identity matrix of size n |
* show identity matrix of size n |
||
Line 3,421: | Line 3,421: | ||
Say ol |
Say ol |
||
End |
End |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,430: | Line 3,430: | ||
</pre> |
</pre> |
||
This could be a 3-dimensional sparse matrix with one element set: |
This could be a 3-dimensional sparse matrix with one element set: |
||
< |
<syntaxhighlight lang="rexx"> |
||
m.=0 |
m.=0 |
||
m.0=1000 /* the matrix' size */ |
m.0=1000 /* the matrix' size */ |
||
m.4.17.333='Walter' |
m.4.17.333='Walter' |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
size = 5 |
size = 5 |
||
im = newlist(size, size) |
im = newlist(size, size) |
||
Line 3,463: | Line 3,463: | ||
next |
next |
||
return alist |
return alist |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,475: | Line 3,475: | ||
Gui version |
Gui version |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Identity Matrix |
# Project : Identity Matrix |
||
# Date : 2022/16/02 |
# Date : 2022/16/02 |
||
Line 3,542: | Line 3,542: | ||
next |
next |
||
score = 0 |
score = 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output image: |
Output image: |
||
Line 3,549: | Line 3,549: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
===Using Array=== |
===Using Array=== |
||
< |
<syntaxhighlight lang="ruby">def identity(size) |
||
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}} |
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}} |
||
end |
end |
||
Line 3,555: | Line 3,555: | ||
[4,5,6].each do |size| |
[4,5,6].each do |size| |
||
puts size, identity(size).map {|r| r.to_s}, "" |
puts size, identity(size).map {|r| r.to_s}, "" |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,581: | Line 3,581: | ||
</pre> |
</pre> |
||
===Using Matrix=== |
===Using Matrix=== |
||
< |
<syntaxhighlight lang="ruby"> |
||
2.1.1 :001 > require "matrix" |
2.1.1 :001 > require "matrix" |
||
=> true |
=> true |
||
2.1.1 :002 > Matrix.identity(5) |
2.1.1 :002 > Matrix.identity(5) |
||
=> Matrix[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] |
=> Matrix[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">' formats array im() of size ims |
||
for ims = 4 to 6 |
for ims = 4 to 6 |
||
Line 3,608: | Line 3,608: | ||
print "]" |
print "]" |
||
next |
next |
||
next ims</ |
next ims</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>--- Size: 4 --- |
<pre>--- Size: 4 --- |
||
Line 3,635: | Line 3,635: | ||
Run with command-line containing the matrix size. |
Run with command-line containing the matrix size. |
||
< |
<syntaxhighlight lang="rust"> |
||
extern crate num; |
extern crate num; |
||
struct Matrix<T> { |
struct Matrix<T> { |
||
Line 3,677: | Line 3,677: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def identityMatrix(n:Int)=Array.tabulate(n,n)((x,y) => if(x==y) 1 else 0) |
||
def printMatrix[T](m:Array[Array[T]])=m map (_.mkString("[", ", ", "]")) mkString "\n" |
def printMatrix[T](m:Array[Array[T]])=m map (_.mkString("[", ", ", "]")) mkString "\n" |
||
printMatrix(identityMatrix(5))</ |
printMatrix(identityMatrix(5))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1, 0, 0, 0, 0] |
<pre>[1, 0, 0, 0, 0] |
||
Line 3,693: | Line 3,693: | ||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
When representing a matrix as a collection of nested lists: |
When representing a matrix as a collection of nested lists: |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (identity n) |
(define (identity n) |
||
(letrec |
(letrec |
||
Line 3,709: | Line 3,709: | ||
(cons (uvec i 0 '()) acc)))))) |
(cons (uvec i 0 '()) acc)))))) |
||
(idgen 0 '()))) |
(idgen 0 '()))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Test program: |
Test program: |
||
< |
<syntaxhighlight lang="scheme"> |
||
(display (identity 4)) |
(display (identity 4)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,720: | Line 3,720: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const type: matrix is array array integer; |
const type: matrix is array array integer; |
||
Line 3,752: | Line 3,752: | ||
begin |
begin |
||
writeMat(identity(6)); |
writeMat(identity(6)); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,765: | Line 3,765: | ||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
< |
<syntaxhighlight lang="sensetalk"> |
||
set matrix to buildIdentityMatrix(3) |
set matrix to buildIdentityMatrix(3) |
||
Line 3,794: | Line 3,794: | ||
return matrixList |
return matrixList |
||
end buildIdentityMatrix |
end buildIdentityMatrix |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output for n 3 |
Output for n 3 |
||
<pre>(1,0,0) |
<pre>(1,0,0) |
||
Line 3,819: | Line 3,819: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func identity_matrix(n) { |
||
n.of { |i| |
n.of { |i| |
||
n.of { |j| |
n.of { |j| |
||
Line 3,832: | Line 3,832: | ||
say row.join(' ') |
say row.join(' ') |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,860: | Line 3,860: | ||
=={{header|Sinclair ZX81 BASIC}}== |
=={{header|Sinclair ZX81 BASIC}}== |
||
Works with 1k of RAM, but for a larger matrix you'll want at least 2k. |
Works with 1k of RAM, but for a larger matrix you'll want at least 2k. |
||
< |
<syntaxhighlight lang="zxbasic"> 10 INPUT S |
||
20 DIM M(S,S) |
20 DIM M(S,S) |
||
30 FOR I=1 TO S |
30 FOR I=1 TO S |
||
Line 3,871: | Line 3,871: | ||
100 NEXT J |
100 NEXT J |
||
110 PRINT |
110 PRINT |
||
120 NEXT I</ |
120 NEXT I</syntaxhighlight> |
||
{{in}} |
{{in}} |
||
<pre>10</pre> |
<pre>10</pre> |
||
Line 3,888: | Line 3,888: | ||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|Pharo Smalltalk}} |
{{works with|Pharo Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">(Array2D identity: (UIManager default request: 'Enter size of the matrix:') asInteger) asString</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 3,898: | Line 3,898: | ||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<syntaxhighlight lang="sparkling">function unitMatrix(n) { |
||
return map(range(n), function(k1, v1) { |
return map(range(n), function(k1, v1) { |
||
return map(range(n), function(k2, v2) { |
return map(range(n), function(k2, v2) { |
||
Line 3,904: | Line 3,904: | ||
}); |
}); |
||
}); |
}); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{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}}== |
=={{header|Stata}}== |
||
=== Stata matrix === |
=== Stata matrix === |
||
< |
<syntaxhighlight lang="stata">. mat a = I(3) |
||
. mat list a |
. mat list a |
||
Line 3,917: | Line 3,917: | ||
r1 1 |
r1 1 |
||
r2 0 1 |
r2 0 1 |
||
r3 0 0 1</ |
r3 0 0 1</syntaxhighlight> |
||
=== Mata === |
=== Mata === |
||
< |
<syntaxhighlight lang="stata">: I(3) |
||
[symmetric] |
[symmetric] |
||
1 2 3 |
1 2 3 |
||
Line 3,927: | Line 3,927: | ||
2 | 0 1 | |
2 | 0 1 | |
||
3 | 0 0 1 | |
3 | 0 0 1 | |
||
+-------------+</ |
+-------------+</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
Line 3,933: | Line 3,933: | ||
{{trans|Elixir}} |
{{trans|Elixir}} |
||
< |
<syntaxhighlight lang="swift">func identityMatrix(size: Int) -> [[Int]] { |
||
return (0..<size).map({i in |
return (0..<size).map({i in |
||
return (0..<size).map({ $0 == i ? 1 : 0}) |
return (0..<size).map({ $0 == i ? 1 : 0}) |
||
Line 3,939: | Line 3,939: | ||
} |
} |
||
print(identityMatrix(size: 5))</ |
print(identityMatrix(size: 5))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,946: | Line 3,946: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
templates identityMatrix |
templates identityMatrix |
||
def n: $; |
def n: $; |
||
Line 3,955: | Line 3,955: | ||
$identity... -> '|$(1);$(2..last)... -> ', $;';| |
$identity... -> '|$(1);$(2..last)... -> ', $;';| |
||
' -> !OUT::write |
' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,967: | Line 3,967: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
When representing a matrix as a collection of nested lists: |
When representing a matrix as a collection of nested lists: |
||
< |
<syntaxhighlight lang="tcl">proc I {rank {zero 0.0} {one 1.0}} { |
||
set m [lrepeat $rank [lrepeat $rank $zero]] |
set m [lrepeat $rank [lrepeat $rank $zero]] |
||
for {set i 0} {$i < $rank} {incr i} { |
for {set i 0} {$i < $rank} {incr i} { |
||
Line 3,973: | Line 3,973: | ||
} |
} |
||
return $m |
return $m |
||
}</ |
}</syntaxhighlight> |
||
Or alternatively with the help of the tcllib package for rectangular data structures: |
Or alternatively with the help of the tcllib package for rectangular data structures: |
||
{{tcllib|struct::matrix}} |
{{tcllib|struct::matrix}} |
||
< |
<syntaxhighlight lang="tcl">package require struct::matrix |
||
proc I {rank {zero 0.0} {one 1.0}} { |
proc I {rank {zero 0.0} {one 1.0}} { |
||
Line 3,988: | Line 3,988: | ||
} |
} |
||
return $m |
return $m |
||
}</ |
}</syntaxhighlight> |
||
Demonstrating the latter: |
Demonstrating the latter: |
||
< |
<syntaxhighlight lang="tcl">set m [I 5 0 1] ;# Integer 0/1 for clarity of presentation |
||
puts [$m format 2string]</ |
puts [$m format 2string]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 0 0 0 0 |
<pre>1 0 0 0 0 |
||
Line 4,000: | Line 4,000: | ||
=={{header|TypeScript}}== |
=={{header|TypeScript}}== |
||
< |
<syntaxhighlight lang="typescript"> |
||
function identity(n) { |
function identity(n) { |
||
if (n < 1) return "Not defined"; |
if (n < 1) return "Not defined"; |
||
Line 4,015: | Line 4,015: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">int main (string[] args) { |
||
if (args.length < 2) { |
if (args.length < 2) { |
||
print ("Please, input an integer > 0.\n"); |
print ("Please, input an integer > 0.\n"); |
||
Line 4,042: | Line 4,042: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Private Function Identity(n As Integer) As Variant |
||
Dim I() As Integer |
Dim I() As Integer |
||
ReDim I(n - 1, n - 1) |
ReDim I(n - 1, n - 1) |
||
Line 4,052: | Line 4,052: | ||
Next j |
Next j |
||
Identity = I |
Identity = I |
||
End Function</ |
End Function</syntaxhighlight> |
||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
build_matrix(7) |
build_matrix(7) |
||
Line 4,085: | Line 4,085: | ||
Next |
Next |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 4,101: | Line 4,101: | ||
'''Alternate version''' |
'''Alternate version''' |
||
< |
<syntaxhighlight lang="vbscript"> |
||
n = 8 |
n = 8 |
||
Line 4,117: | Line 4,117: | ||
Identity = a |
Identity = a |
||
End Function |
End Function |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 4,132: | Line 4,132: | ||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
{{works with|Visual Basic|6}} |
{{works with|Visual Basic|6}} |
||
< |
<syntaxhighlight lang="vb">Option Explicit |
||
'------------ |
'------------ |
||
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte() |
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte() |
||
Line 4,170: | Line 4,170: | ||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>10000 |
<pre>10000 |
||
Line 4,190: | Line 4,190: | ||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@let { |
||
im ^(%^\@table ^(@+ =) @to) |
im ^(%^\@table ^(@+ =) @to) |
||
!im 4 |
!im 4 |
||
}</ |
}</syntaxhighlight> |
||
Returns: |
Returns: |
||
<pre>[[1 0 0 0] |
<pre>[[1 0 0 0] |
||
Line 4,204: | Line 4,204: | ||
{{libheader|Wren-matrix}} |
{{libheader|Wren-matrix}} |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/matrix" for Matrix |
||
import "/fmt" for Fmt |
import "/fmt" for Fmt |
||
var numRows = 10 // say |
var numRows = 10 // say |
||
Fmt.mprint(Matrix.identity(numRows), 2, 0)</ |
Fmt.mprint(Matrix.identity(numRows), 2, 0)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,225: | Line 4,225: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
def IntSize = 4; \number of bytes in an integer |
def IntSize = 4; \number of bytes in an integer |
||
int Matrix, Size, I, J; |
int Matrix, Size, I, J; |
||
Line 4,241: | Line 4,241: | ||
CrLf(0); |
CrLf(0); |
||
]; |
]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,255: | Line 4,255: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Using lists of lists: |
Using lists of lists: |
||
< |
<syntaxhighlight lang="zkl">fcn idMatrix(n){ |
||
m:=(0).pump(n,List.createLong(n).write,0)*n; |
m:=(0).pump(n,List.createLong(n).write,0)*n; |
||
m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0)); |
m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0)); |
||
Line 4,261: | Line 4,261: | ||
} |
} |
||
idMatrix(5).println(); |
idMatrix(5).println(); |
||
idMatrix(5).pump(Console.println);</ |
idMatrix(5).pump(Console.println);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,274: | Line 4,274: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
{{trans|Applesoft_BASIC}} |
{{trans|Applesoft_BASIC}} |
||
< |
<syntaxhighlight lang="zxbasic">10 INPUT "Matrix size: ";size |
||
20 GO SUB 200: REM Identity matrix |
20 GO SUB 200: REM Identity matrix |
||
30 FOR r=1 TO size |
30 FOR r=1 TO size |
||
Line 4,289: | Line 4,289: | ||
240 LET i(i,i)=1 |
240 LET i(i,i)=1 |
||
250 NEXT i |
250 NEXT i |
||
260 RETURN</ |
260 RETURN</syntaxhighlight> |