Anonymous user
Identity matrix: Difference between revisions
m
→{{header|Elena}}
Drkameleon (talk | contribs) (Added Arturo implementation) |
imported>Arakov |
||
(13 intermediate revisions by 10 users not shown) | |||
Line 29:
{{trans|Python}}
<
V matrix = [[0] * size] * size
L(i) 0 .< size
Line 36:
L(row) identity_matrix(3)
print(row)</
{{out}}
Line 46:
=={{header|360 Assembly}}==
<
INDENMAT CSECT
USING INDENMAT,R13 base register
Line 118:
A DS F a(n,n)
YREGS
END INDENMAT</
{{out}}
<pre>
Line 134:
=={{header|Action!}}==
<
CARD pos
BYTE i,j
Line 191:
LMARGIN=old ;restore left margin on the screen
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Identity_matrix.png Screenshot from Atari 8-bit computer]
Line 213:
=={{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.
<
-- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix;
-- For the task:
mat : Real_Matrix := Unit_Matrix(5);</
For prior versions of Ada, or non floating point types its back to basics:
<
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;</
=={{header|ALGOL 68}}==
Line 229:
'''Note:''' The generic vector and matrix code should be moved to a more generic page.
'''File: prelude/vector_base.a68'''<
# -*- coding: utf-8 -*- #
Line 261:
);
SKIP</
# Define some generic matrix initialisation and printing operations #
Line 312:
);
SKIP</
PRIO IDENT = 9; # The same as I for COMPLex #
Line 322:
1 IDENT upb;
SKIP</
# -*- coding: utf-8 -*- #
Line 329:
PR READ "prelude/matrix_ident.a68" PR;
SKIP</
# -*- coding: utf-8 -*- #
Line 337:
PR READ "prelude/matrix.a68" PR;
print(REPR IDENT 4)</
{{out}}
<pre>
Line 347:
=={{header|ALGOL W}}==
<
% set m to an identity matrix of size s %
procedure makeIdentity( real array m ( *, * )
Line 368:
end text
end.</
=={{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 374 ⟶ 431:
For a square matrix of 3:
<
∘.=⍨⍳3
1 0 0
0 1 0
0 0 1
</syntaxhighlight>
For a function that makes an identity matrix:
<
ID←{∘.=⍨⍳⍵}
ID 5
Line 390 ⟶ 447:
0 0 0 1 0
0 0 0 0 1
</syntaxhighlight>
An tacit function can be defined with one of the following equivalent lines:
<
ID←∘.=⍨⍳
ID←⍳∘.=⍳
</syntaxhighlight>
There is a more idomatic way however:
<
ID←{⍵ ⍵ ρ 1, ⍵ρ0}
</syntaxhighlight>
=={{header|AppleScript}}==
<
-- identityMatrix :: Int -> [(0|1)]
Line 511 ⟶ 568:
set my text item delimiters to dlm
s
end unlines</
{{Out}}
<pre>[1, 0, 0, 0, 0]
Line 520 ⟶ 577:
----
===Simple alternative===
<
set digits to {}
set m to n - 1
Line 536 ⟶ 593:
end indentityMatrix
return indentityMatrix(5)</
{{output}}
<
=={{header|Arturo}}==
<
result: array.of: @[n n] 0
loop 0..dec n 'i -> result\[i]\[i]: 1
Line 553 ⟶ 610:
loop identityM sz => print
print ""
]</
{{out}}
Line 580 ⟶ 637:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoft basic">
100 INPUT "MATRIX SIZE:"; SIZE%
110 GOSUB 200"IDENTITYMATRIX
Line 596 ⟶ 653:
240 LET IM(I, I) = 1 : NEXT I
250 RETURN :IM
</syntaxhighlight>
==={{header|Commodore BASIC}}===
{{trans|Applesoft BASIC}}
{{works with|Commodore BASIC|2.0}}
<
110 GOSUB 200: REM IDENTITYMATRIX
120 FOR R = 0 TO SIZE
130 FOR C = 0 TO SIZE
140
150 IF C < SIZE
160 PRINT MID$(STR$(IM(R, C)
170 NEXT C, R
180 END
190 REM *******************************
200 REM IDENTITYMATRIX SIZE%
210 SIZE
220 DIM IM(SIZE
230 FOR I = 0 TO SIZE
240 IM(I, I) = 1
250 NEXT I
260 RETURN</
==={{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">
(* ****** ****** *)
//
Line 654 ⟶ 840:
//
} (* end of [main0] *)
</syntaxhighlight>
=={{header|AutoHotkey}}==
<
return
Line 672 ⟶ 858:
s .= " "
return Rtrim(r,"`n") "`n" s "--"
}</
{{out}}
Line 687 ⟶ 873:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
Line 705 ⟶ 891:
exit(0)
}
</syntaxhighlight>
{{out}} for command: GAWK -f IDENTITY_MATRIX.AWK 5
<pre>
Line 716 ⟶ 902:
=={{header|Bash}}==
<syntaxhighlight lang="bash">
for i in `seq $1`;do printf '%*s\n' $1|tr ' ' '0'|sed "s/0/1/$i";done
</syntaxhighlight>
{{out}} for command: ./scriptname 5
<pre>
Line 730 ⟶ 916:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PROCidentitymatrix(size%, im())
FOR r% = 0 TO size%-1
Line 746 ⟶ 932:
m(i%,i%) = 1
NEXT
ENDPROC</
=={{header|Beads}}==
<
var
Line 758 ⟶ 944:
loop from:1 to:n index:i
loop from:1 to:n index:j
id[i,j] = 1 if i == j else 0</
{{out}}
Line 773 ⟶ 959:
Neither very elegant nor short but it'll do
<
blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp
1 0 0 0 0 0
Line 781 ⟶ 967:
0 0 0 0 1 0
0 0 0 0 0 1
</syntaxhighlight>
The example above uses strings to generate the identity matrix. If you need a matrix with real numbers (Integers) then use:
<
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e!
</syntaxhighlight>
Shorter alternative:
<
blsq ) 6 ^^^^10\/**XXcy\/co.+sp
</syntaxhighlight>
=={{header|BQN}}==
<syntaxhighlight lang="text">⍝ Using table
Eye ← =⌜˜∘↕
•Show Eye 3
Line 802 ⟶ 988:
⍝ Using reshape
Eye1 ← {𝕩‿𝕩⥊1∾𝕩⥊0}
Eye1 5</
<syntaxhighlight lang="text">┌─
╵ 1 0 0
0 1 0
Line 815 ⟶ 1,001:
0 0 0 0 1
┘
</syntaxhighlight>
<code>Eye</code> generates an identity matrix using a table of equality for [0,n).
Line 824 ⟶ 1,010:
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdlib.h>
#include <stdio.h>
Line 863 ⟶ 1,049:
}
}
</syntaxhighlight>
=={{header|C sharp}}==
<
using System;
using System.Linq;
Line 902 ⟶ 1,088:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 915 ⟶ 1,101:
=={{header|C++}}==
{{libheader|STL}}
<
class matrix
{
Line 962 ⟶ 1,148:
return 0;
}
</syntaxhighlight>
{{libheader|boost}}
<
#include <boost/numeric/ublas/matrix.hpp>
Line 988 ⟶ 1,174:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,000 ⟶ 1,186:
=={{header|Clio}}==
<
[0:n] -> * fn i:
[0:n] -> * if = i: 1
else: 0
5 -> identity-matrix -> * print</
=={{header|Clojure}}==
Line 1,011 ⟶ 1,197:
The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g.
<
</syntaxhighlight>
, then care to remove the vec function.
<
(let [row (conj (repeat (dec n) 0) 1)]
(vec
Line 1,020 ⟶ 1,206:
(vec
(reduce conj (drop i row ) (take i row)))))))
</syntaxhighlight>
{{out}}
<
[[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>
The following is a more idomatic definition that utilizes infinite lists and cycling.
<
(defn identity-matrix [n]
(take n
(partition n (dec n)
(cycle (conj (repeat (dec n) 0) 1)))))
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 1,038 ⟶ 1,224:
Common Lisp provides multi-dimensional arrays.
<
(let ((array (make-array (list n n) :initial-element 0)))
(loop for i below n do (setf (aref array i i) 1))
array))
</syntaxhighlight>
{{out}}
Line 1,048 ⟶ 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))
<
(loop for a from 1 to n
collect (loop for e from 1 to n
if (= a e) collect 1
else collect 0)))
</syntaxhighlight>
{{out}}
Line 1,063 ⟶ 1,249:
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE Algebras;
IMPORT StdLog,Strings;
Line 1,099 ⟶ 1,285:
END Do;
END Algebras.
</syntaxhighlight>
Execute: ^Q Algebras.Do<br/>
{{out}}
Line 1,111 ⟶ 1,297:
=={{header|D}}==
<
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
Line 1,140 ⟶ 1,326:
// auto id3 = matId!(const int)(2); // cant't compile
}</
{{out}}
<pre>[[1, 0, 0, 0, 0],
Line 1,153 ⟶ 1,339:
=={{header|Delphi}}==
<
// Modified from the Pascal version
Line 1,177 ⟶ 1,363:
writeln;
end;
end.</
{{out}}
<pre>
Line 1,187 ⟶ 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">
class
APPLICATION
Line 1,251 ⟶ 1,450:
end
</syntaxhighlight>
{{out}}
Line 1,268 ⟶ 1,467:
=={{header|Elena}}==
ELENA
<
import system'routines;
import system'collections;
Line 1,275 ⟶ 1,474:
public program()
{
var n := console.write
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()) }
}</
{{out}}
<pre>
Line 1,292 ⟶ 1,491:
=={{header|Elixir}}==
<
def identity(n) do
Enum.map(0..n-1, fn i ->
Line 1,300 ⟶ 1,499:
end
IO.inspect Matrix.identity(5)</
{{out}}
Line 1,309 ⟶ 1,508:
=={{header|Erlang}}==
<
%% Implemented by Arjun Sunel
Line 1,319 ⟶ 1,518:
identity(Size) ->
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM IDENTITY
Line 1,343 ⟶ 1,542:
END FOR
END PROGRAM
</syntaxhighlight>
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
function IdentityMatrix(n)
$ X:=zeros(n,n);
Line 1,355 ⟶ 1,554:
$ return X;
$endfunction
</syntaxhighlight>
<syntaxhighlight lang="euler math toobox">
>function IdentityMatrix (n:index)
$ return setdiag(zeros(n,n),0,1);
$endfunction
</syntaxhighlight>
<syntaxhighlight lang="text">
>id(5)
</syntaxhighlight>
=={{header|Excel}}==
Line 1,377 ⟶ 1,576:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(n,
LET(
Line 1,389 ⟶ 1,588:
)
)
)</
{{Out}}
Line 1,487 ⟶ 1,686:
=={{header|F Sharp|F#}}==
Builds a 2D matrix with the given square size.
<syntaxhighlight lang="fsharp">
let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0)
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="fsharp">
ident 10;;
val it : int [,] = [[1; 0; 0; 0; 0; 0; 0; 0; 0; 0]
Line 1,504 ⟶ 1,703:
[0; 0; 0; 0; 0; 0; 0; 0; 1; 0]
[0; 0; 0; 0; 0; 0; 0; 0; 0; 1]]
</syntaxhighlight>
=={{header|Factor}}==
{{works with|Factor|0.99 2020-07-03}}
<
6 <identity-matrix> .</
{{out}}
<pre>
Line 1,562 ⟶ 1,761:
=={{header|Fermat}}==
<
Func Identity(n)=Array id[n,n];[id]:=[1].
Identity(7)
[id]
</syntaxhighlight>
{{out}}
<pre>
Line 1,581 ⟶ 1,780:
{{libheader|Forth Scientific Library}}
{{works with|gforth|0.7.9_20170308}}
<
: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix
Line 1,596 ⟶ 1,795:
6 6 float matrix a{{
a{{ 6 build-identity
6 6 a{{ }}fprint</
=={{header|Fortran}}==
{{works with|Fortran|95}}
<
program identitymatrix
Line 1,625 ⟶ 1,824:
end program identitymatrix
</syntaxhighlight>
===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.
<
Integer N
Parameter (N = 666)
Line 1,637 ⟶ 1,836:
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i)
END</
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:
<
DO 1 J = 1,N
1 A(I,J) = (I/J)*(J/I)</
Array assignment statements are also a feature of F90 and later.
Line 1,648 ⟶ 1,847:
=={{header|FreeBASIC}}==
<
Dim As Integer n
Line 1,679 ⟶ 1,878:
Print
Print "Press any key to quit"
Sleep</
Sample input/output
{{out}}
Line 1,695 ⟶ 1,894:
This does not use the Matrix.frink library, which has methods to create an identity matrix, but shows how to build a "raw" identity matrix as a two-dimensional array, and shows how to nicely format it using built-in routines.
<
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]</
{{out}}
Line 1,711 ⟶ 1,910:
=={{header|FunL}}==
<
println( identity(3) )</
{{out}}
Line 1,723 ⟶ 1,922:
=={{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}}==
<
IdentityMat(3);
# One can also specify the base ring
IdentityMat(3, Integers mod 10);</
=={{header|Go}}==
===Library gonum/mat===
<
import (
Line 1,756 ⟶ 2,026:
func main() {
fmt.Println(mat.Formatted(eye(3)))
}</
{{out}}
<pre>
Line 1,766 ⟶ 2,036:
===Library go.matrix===
A somewhat earlier matrix library for Go.
<
import (
Line 1,776 ⟶ 2,046:
func main() {
fmt.Println(mat.Eye(3))
}</
{{out}}
<pre>
Line 1,786 ⟶ 2,056:
===From scratch===
'''Simplest: ''' A matrix as a slice of slices, allocated separately.
<
import "fmt"
Line 1,802 ⟶ 2,072:
}
return m
}</
{{out}}
No special formatting method used.
Line 1,810 ⟶ 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.
<
import "fmt"
Line 1,827 ⟶ 2,097:
}
return m
}</
{{out}}
Line 1,833 ⟶ 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.
<
import "fmt"
Line 1,866 ⟶ 2,136:
}
return m
}</
{{out}}
<pre>
Line 1,877 ⟶ 2,147:
=={{header|Groovy}}==
Solution:
<
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }
}</
Test:
<
def iMatrix = makeIdentityMatrix(order)
iMatrix.each { println it }
println()
}</
{{out}}
Line 1,915 ⟶ 2,185:
=={{header|Haskell}}==
<
And a function to show matrix pretty:
<
showMat = unlines . map (unwords . map show)</
<
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
Line 1,931 ⟶ 2,201:
0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1
</syntaxhighlight>
We could alternatively bypassing the syntactic sugaring of list comprehension notation, and use a bind function directly:
<
idMatrix n =
let xs = [1 .. n]
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]</
or reduce the number of terms a little to:
<
idMatrix n =
let xs = [1 .. n]
Line 1,947 ⟶ 2,217:
main :: IO ()
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5</
{{Out}}
<pre>1 0 0 0 0
Line 1,958 ⟶ 2,228:
This code works for Icon and Unicon.
<
procedure main(argv)
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.")
Line 1,964 ⟶ 2,234:
write_matrix(&output,matrix1)
end
</syntaxhighlight>
{{out}}
Line 1,979 ⟶ 2,249:
=={{header|IS-BASIC}}==
<
110 INPUT PROMPT "Enter size of matrix: ":N
120 NUMERIC A(1 TO N,1 TO N)
Line 1,999 ⟶ 2,269:
280 PRINT
290 NEXT
300 END DEF</
=={{header|J}}==
<
1 0 0 0
0 1 0 0
Line 2,013 ⟶ 2,283:
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1</
=={{header|Java}}==
<
public static void main(String[] args) {
Line 2,028 ⟶ 2,298:
.forEach(System.out::println);
}
}</
{{out}}
Line 2,041 ⟶ 2,311:
===ES5===
<
return Array.apply(null, new Array(n))
.map(function (x, i, xs) {
Line 2,048 ⟶ 2,318:
})
});
}</
===ES6===
<
// identityMatrix :: Int -> [[Int]]
Line 2,066 ⟶ 2,336:
.map(JSON.stringify)
.join('\n');
})();</
{{Out}}
<pre>[1,0,0,0,0]
Line 2,076 ⟶ 2,346:
=={{header|jq}}==
===Construction===
<
[range(0;n) | 0] as $row
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</
Example:
<syntaxhighlight lang
[[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]]:
<
reduce range(0;n) as $i
(0 | matrix(n;n); .[$i][$i] = 1);
</syntaxhighlight>
=={{header|Jsish}}==
<
function identityMatrix(n) {
var mat = new Array(n).fill(0);
Line 2,123 ⟶ 2,393:
[ 0, 0, 0, 1 ]
=!EXPECTEND!=
*/</
{{out}}
Line 2,133 ⟶ 2,403:
representing an identity matrix of any size,
boolean by default, that can be multiplied by a scalar
<
unitfloat64matrix = 1.0I</
UniformScaling object can be used as a function to construct a Diagonal
matrix of given size, that can be converted to a full matrix using <tt>collect</tt>
<
diagI3 = 1.0I(3)
fullI3 = collect(diagI3)</
The function I(3) is not defined in Julia-1.0.5. Other ways to construct a full matrix of given size are
<
fullI3 = Matrix{Float64}(I, 3, 3)
fullI3 = Array{Float64}(I, 3, 3)
fullI3 = Array{Float64,2}(I, 3, 3)
fullI3 = zeros(3,3) + I</
=={{header|K}}==
<
(1 0 0 0
0 1 0 0
Line 2,163 ⟶ 2,433:
0 0 0 1 0
0 0 0 0 1)
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 2,182 ⟶ 2,452:
else
println("Matrix is too big to display on 80 column console")
}</
Sample input/output
{{out}}
Line 2,196 ⟶ 2,466:
=={{header|Lambdatalk}}==
<
{def identity
{lambda {:n}
Line 2,211 ⟶ 2,481:
{identity 5}
-> [[1,0,0,0,0],[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1]]
</syntaxhighlight>
=={{header|Lang5}}==
<
dup iota 'A set
Line 2,222 ⟶ 2,492:
;
5 identity-matrix .</
{{out}}
<pre>[
Line 2,234 ⟶ 2,504:
=={{header|LFE}}==
<
(defun identity
((`(,m ,n))
Line 2,243 ⟶ 2,513:
(defun identity (m n)
(lists:duplicate m (lists:duplicate n 1)))
</syntaxhighlight>
From the LFE REPL; note that the last two usage examples demonstrate how identify could be used when composed with functions that get the dimension of a matrix:
<
> (identity 3)
((1 1 1) (1 1 1) (1 1 1))
Line 2,255 ⟶ 2,525:
((1 1 1) (1 1 1) (1 1 1))
</syntaxhighlight>
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
<
state_entry() {
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
Line 2,277 ⟶ 2,547:
}
}
}</
{{out}}
<pre>You: 0
Line 2,298 ⟶ 2,568:
=={{header|Lua}}==
<
function identity_matrix (size)
local m = {}
Line 2,316 ⟶ 2,586:
end
print_matrix(identity_matrix(5))</
{{out}}
<pre>
Line 2,327 ⟶ 2,597:
=={{header|Maple}}==
One of a number of ways to do this:
<syntaxhighlight lang="maple">
> LinearAlgebra:-IdentityMatrix( 4 );
[1 0 0 0]
Line 2,336 ⟶ 2,606:
[ ]
[0 0 0 1]
</syntaxhighlight>
Here, for instance, is another, in which the entries are (4-byte) floats.
<syntaxhighlight lang="maple">
> Matrix( 4, shape = scalar[1], datatype = float[4] );
[1. 0. 0. 0.]
Line 2,347 ⟶ 2,617:
[ ]
[0. 0. 0. 1.]
</syntaxhighlight>
Yet another, with 2-byte integer entries:
<syntaxhighlight lang="maple">
> Matrix( 4, shape = identity, datatype = integer[ 2 ] );
[1 0 0 0]
Line 2,358 ⟶ 2,628:
[ ]
[0 0 0 1]
</syntaxhighlight>
=={{header|MathCortex}}==
<
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang
=={{header|MATLAB}} / {{header|Octave}}==
The '''eye''' function create the identity (I) matrix, e.g.:
<
=={{header|Maxima}}==
<
/* matrix([1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]) */</
=={{header|NetRexx}}==
===Using int Array===
{{trans|REXX}}
<
* show identity matrix of size n
* I consider m[i,j] to represent the matrix
Line 2,400 ⟶ 2,670:
Say ol
End
</syntaxhighlight>
===Using Indexed String===
<
options replace format comments java crossref symbols nobinary
Line 2,440 ⟶ 2,710:
displayIdMatrix(createIdMatrix(n))
return
</syntaxhighlight>
=={{header|Nim}}==
<
result = newSeq[seq[int]](n)
for i in 0 ..< result.len:
result[i] = newSeq[int](n)
result[i][i] = 1</
=={{header|Objeck}}==
<
function : Matrix(n : Int) ~ Int[,] {
array := Int->New[n,n];
Line 2,482 ⟶ 2,752:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
Line 2,488 ⟶ 2,758:
From the interactive loop (that we call the "toplevel"):
<
# let make_id_matrix n =
Line 2,504 ⟶ 2,774:
[|0.; 1.; 0.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 0.; 1.|] |]</
another way:
<
Array.init n (fun i ->
Array.init n (fun j ->
Line 2,520 ⟶ 2,790:
[|0.; 1.; 0.; 0.|];
[|0.; 0.; 1.; 0.|];
[|0.; 0.; 0.; 1.|] |]</
When we write a function in the toplevel, it returns us its signature (the prototype), and when we write a variable (or a function call), it returns its type and its value.
Line 2,527 ⟶ 2,797:
The '''eye''' function create the identity (I) matrix, e.g.:
<
=={{header|Ol}}==
<
(define (make-identity-matrix n)
(map (lambda (i)
Line 2,537 ⟶ 2,807:
(for-each print (make-identity-matrix 3))
(for-each print (make-identity-matrix 17))</
{{out}}
<pre>
Line 2,563 ⟶ 2,833:
=={{header|ooRexx}}==
ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays.
<syntaxhighlight lang="oorexx">
say "a 3x3 identity matrix"
say
Line 2,593 ⟶ 2,863:
say line
end i
</syntaxhighlight>
{{out}}
<pre style="height:20ex;overflow:scroll">
Line 2,612 ⟶ 2,882:
=={{header|OxygenBasic}}==
<
Class SquareMatrix
'=================
Line 2,643 ⟶ 2,913:
'...
del M
</syntaxhighlight>
=={{header|PARI/GP}}==
Built-in:
<syntaxhighlight lang
Custom:
<
=={{header|Pascal}}==
<
var
Line 2,673 ⟶ 2,943:
writeln;
end;
end.</
{{out}}
<pre>
Line 2,686 ⟶ 2,956:
=={{header|Perl}}==
<
use warnings;
use feature 'say';
Line 2,698 ⟶ 2,968:
say "\n$_:";
say join ' ', @$_ for identity_matrix $_;
}</
{{out}}
<pre>4:
Line 2,722 ⟶ 2,992:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 2,736 ⟶ 3,006:
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">identity</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">))</span>
<!--</
{{out}}
<pre style="float:left">
Line 2,772 ⟶ 3,042:
=={{header|PHP}}==
<
function identity($length) {
return array_map(function($key, $value) {$value[$key] = 1; return $value;}, range(0, $length-1),
Line 2,781 ⟶ 3,051:
}
print_identity(identity(10));
</syntaxhighlight>
{{out}}
<pre>
Line 2,797 ⟶ 3,067:
=={{header|PicoLisp}}==
<
(let L (need Size (1) 0)
(make
(do Size
(link (copy (rot L))) ) ) ) )</
Test:
<
-> ((1 0 0) (0 1 0) (0 0 1))
Line 2,811 ⟶ 3,081:
(0 0 1 0 0)
(0 0 0 1 0)
(0 0 0 0 1)</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
identity: procedure (A, n);
declare A(n,n) fixed controlled;
Line 2,821 ⟶ 3,091:
do i = 1 to n; A(i,i) = 1; end;
end identity;
</syntaxhighlight>
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
% n ident [identity-matrix]
% create an identity matrix of dimension n*n.
Line 2,841 ⟶ 3,111:
]
end } def
</syntaxhighlight>
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function identity($n) {
0..($n-1) | foreach{$row = @(0) * $n; $row[$_] = 1; ,$row}
Line 2,851 ⟶ 3,121:
$array = identity 4
show $array
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,859 ⟶ 3,129:
0 0 0 1
</pre>
<syntaxhighlight lang="powershell">
$array[0][0]
$array[0][1]
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,873 ⟶ 3,143:
=={{header|Prolog}}==
{{Works with|SWi-Prolog}}
<
rotate(Int,List,Rotated) :-
integer(Int),
Line 2,902 ⟶ 3,172:
idmatrix(5,I),
maplist(writeln,I).
</syntaxhighlight>
{{out}}
Line 2,915 ⟶ 3,185:
=={{header|PureBasic}}==
<
;formats array i() as an identity matrix of size x size
Dim i(size - 1, size - 1)
Line 2,951 ⟶ 3,221:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre> 1 0 0
Line 2,965 ⟶ 3,235:
===Nested lists===
A simple solution, using nested lists to represent the matrix.
<
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,975 ⟶ 3,245:
for elements in rows:
print elements,
print ""</
===Nested maps and comprehensions===
{{Works with|Python|3.7}}
<
import operator
Line 3,039 ⟶ 3,309:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>idMatrix:
Line 3,059 ⟶ 3,329:
===Dict of points===
A dict of tuples of two ints (x, y) are used to represent the matrix.
<
... return {(x, y):int(x == y) for x in range(size) for y in range(size)}
...
Line 3,069 ⟶ 3,339:
0 0 1 0
0 0 0 1
>>> </
===Numpy===
A solution using the numpy library
<
np.mat(np.eye(size))
</syntaxhighlight>
=={{header|Quackery}}==
<
[ 0 i^ of 1 join 0 i of
join nested join ] ] is identity ( n --> [ )
5 identity echo</
{{out}}
<pre>
Line 3,091 ⟶ 3,361:
When passed a single scalar argument, <code>diag</code> produces an identity matrix of size given by the scalar. For example:
<syntaxhighlight lang
produces:
Line 3,100 ⟶ 3,370:
[3,] 0 0 1</pre>
Or you can also use the method that is shown below
<
x=matrix(0,size,size)
for (i in 1:size) {
Line 3,106 ⟶ 3,376:
}
return(x)
}</
=={{header|Racket}}==
<
#lang racket
(require math)
(identity-matrix 5)
</syntaxhighlight>
{{out}}
<pre>
Line 3,126 ⟶ 3,396:
(formerly Perl 6)
{{works with|rakudo|2015-09-15}}
<syntaxhighlight lang="raku"
my @id;
for flat ^$n X ^$n -> $i, $j {
Line 3,134 ⟶ 3,404:
}
.say for identity-matrix(5);</
{{out}}
<pre>[1 0 0 0 0]
Line 3,142 ⟶ 3,412:
[0 0 0 0 1]</pre>
On the other hand, this may be clearer and/or faster:
<syntaxhighlight lang="raku"
my @id = [0 xx $n] xx $n;
@id[$_][$_] = 1 for ^$n;
@id;
}</
Here is yet an other way to do it:
<syntaxhighlight lang="raku"
[1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
}</
=={{header|Red}}==
<
identity-matrix: function [size][
Line 3,165 ⟶ 3,435:
]
probe identity-matrix 5</
{{out}}
<pre>
Line 3,183 ⟶ 3,453:
It also tries to display a centered (and easier to read) matrix, along with a title.
<
do k=3 to 6 /* [↓] build and display a sq. matrix.*/
call ident_mat k /*build & display a KxK square matrix. */
Line 3,212 ⟶ 3,482:
say _ /*display a single line of the matrix. */
end /*row*/
return</
{{out|output|text= when using the default sizes (3 ──► 6) for generating four matrices:}}
<pre>
Line 3,248 ⟶ 3,518:
===version 2===
An alternative?!
<
/* REXX ***************************************************************
* show identity matrix of size n
Line 3,265 ⟶ 3,535:
Say ol
End
</syntaxhighlight>
{{out}}
<pre>
Line 3,274 ⟶ 3,544:
</pre>
This could be a 3-dimensional sparse matrix with one element set:
<
m.=0
m.0=1000 /* the matrix' size */
m.4.17.333='Walter'
</syntaxhighlight>
=={{header|Ring}}==
<
size = 5
im = newlist(size, size)
Line 3,307 ⟶ 3,577:
next
return alist
</syntaxhighlight>
Output:
<pre>
Line 3,319 ⟶ 3,589:
Gui version
<
# Project : Identity Matrix
# Date : 2022/16/02
Line 3,386 ⟶ 3,656:
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===
<
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}
end
Line 3,399 ⟶ 3,681:
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s}, ""
end</
{{out}}
Line 3,425 ⟶ 3,707:
</pre>
===Using Matrix===
<
p Matrix.identity(5)
# => Matrix[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]
</syntaxhighlight>
=={{header|Run BASIC}}==
<
for ims = 4 to 6
Line 3,452 ⟶ 3,733:
print "]"
next
next ims</
{{out}}
<pre>--- Size: 4 ---
Line 3,479 ⟶ 3,760:
Run with command-line containing the matrix size.
<
extern crate num;
struct Matrix<T> {
Line 3,521 ⟶ 3,802:
}
}
</syntaxhighlight>
=={{header|Scala}}==
<
def printMatrix[T](m:Array[Array[T]])=m map (_.mkString("[", ", ", "]")) mkString "\n"
printMatrix(identityMatrix(5))</
{{out}}
<pre>[1, 0, 0, 0, 0]
Line 3,537 ⟶ 3,818:
=={{header|Scheme}}==
When representing a matrix as a collection of nested lists:
<
(define (identity n)
(letrec
Line 3,553 ⟶ 3,834:
(cons (uvec i 0 '()) acc))))))
(idgen 0 '())))
</syntaxhighlight>
Test program:
<
(display (identity 4))
</syntaxhighlight>
{{out}}
<pre>
Line 3,564 ⟶ 3,845:
=={{header|Seed7}}==
<
const type: matrix is array array integer;
Line 3,596 ⟶ 3,877:
begin
writeMat(identity(6));
end func;</
{{out}}
Line 3,609 ⟶ 3,890:
=={{header|SenseTalk}}==
<
set matrix to buildIdentityMatrix(3)
Line 3,638 ⟶ 3,919:
return matrixList
end buildIdentityMatrix
</syntaxhighlight>
Output for n 3
<pre>(1,0,0)
Line 3,663 ⟶ 3,944:
=={{header|Sidef}}==
<
n.of { |i|
n.of { |j|
Line 3,676 ⟶ 3,957:
say row.join(' ')
}
}</
{{out}}
Line 3,704 ⟶ 3,985:
=={{header|Sinclair ZX81 BASIC}}==
Works with 1k of RAM, but for a larger matrix you'll want at least 2k.
<
20 DIM M(S,S)
30 FOR I=1 TO S
Line 3,715 ⟶ 3,996:
100 NEXT J
110 PRINT
120 NEXT I</
{{in}}
<pre>10</pre>
Line 3,732 ⟶ 4,013:
=={{header|Smalltalk}}==
{{works with|Pharo Smalltalk}}
<
{{Out}}
<pre>
Line 3,742 ⟶ 4,023:
=={{header|Sparkling}}==
<
return map(range(n), function(k1, v1) {
return map(range(n), function(k2, v2) {
Line 3,748 ⟶ 4,029:
});
});
}</
=={{header|Standard ML}}==
<
=={{header|Stata}}==
=== Stata matrix ===
<
. mat list a
Line 3,761 ⟶ 4,042:
r1 1
r2 0 1
r3 0 0 1</
=== Mata ===
<
[symmetric]
1 2 3
Line 3,771 ⟶ 4,052:
2 | 0 1 |
3 | 0 0 1 |
+-------------+</
=={{header|Swift}}==
Line 3,777 ⟶ 4,058:
{{trans|Elixir}}
<
return (0..<size).map({i in
return (0..<size).map({ $0 == i ? 1 : 0})
Line 3,783 ⟶ 4,064:
}
print(identityMatrix(size: 5))</
{{out}}
Line 3,790 ⟶ 4,071:
=={{header|Tailspin}}==
<
templates identityMatrix
def n: $;
Line 3,799 ⟶ 4,080:
$identity... -> '|$(1);$(2..last)... -> ', $;';|
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,811 ⟶ 4,092:
=={{header|Tcl}}==
When representing a matrix as a collection of nested lists:
<
set m [lrepeat $rank [lrepeat $rank $zero]]
for {set i 0} {$i < $rank} {incr i} {
Line 3,817 ⟶ 4,098:
}
return $m
}</
Or alternatively with the help of the tcllib package for rectangular data structures:
{{tcllib|struct::matrix}}
<
proc I {rank {zero 0.0} {one 1.0}} {
Line 3,832 ⟶ 4,113:
}
return $m
}</
Demonstrating the latter:
<
puts [$m format 2string]</
{{out}}
<pre>1 0 0 0 0
Line 3,844 ⟶ 4,125:
=={{header|TypeScript}}==
<
function identity(n) {
if (n < 1) return "Not defined";
Line 3,859 ⟶ 4,140:
}
}
</syntaxhighlight>
=={{header|Vala}}==
<
if (args.length < 2) {
print ("Please, input an integer > 0.\n");
Line 3,886 ⟶ 4,167:
}
return 0;
}</
=={{header|VBA}}==
<
Dim I() As Integer
ReDim I(n - 1, n - 1)
Line 3,896 ⟶ 4,177:
Next j
Identity = I
End Function</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
build_matrix(7)
Line 3,929 ⟶ 4,210:
Next
End Sub
</syntaxhighlight>
{{Out}}
Line 3,945 ⟶ 4,226:
'''Alternate version'''
<
n = 8
Line 3,961 ⟶ 4,242:
Identity = a
End Function
</syntaxhighlight>
{{Out}}
<pre>
Line 3,976 ⟶ 4,257:
=={{header|Visual Basic}}==
{{works with|Visual Basic|6}}
<
'------------
Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte()
Line 4,014 ⟶ 4,295:
End Sub
</syntaxhighlight>
{{out}}
<pre>10000
Line 4,034 ⟶ 4,315:
=={{header|Wortel}}==
<
im ^(%^\@table ^(@+ =) @to)
!im 4
}</
Returns:
<pre>[[1 0 0 0]
Line 4,048 ⟶ 4,329:
{{libheader|Wren-matrix}}
{{libheader|Wren-fmt}}
<
import "./fmt" for Fmt
var numRows = 10 // say
Fmt.mprint(Matrix.identity(numRows), 2, 0)</
{{out}}
Line 4,069 ⟶ 4,350:
=={{header|XPL0}}==
<
def IntSize = 4; \number of bytes in an integer
int Matrix, Size, I, J;
Line 4,085 ⟶ 4,366:
CrLf(0);
];
]</
{{out}}
Line 4,099 ⟶ 4,380:
=={{header|zkl}}==
Using lists of lists:
<
m:=(0).pump(n,List.createLong(n).write,0)*n;
m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0));
Line 4,105 ⟶ 4,386:
}
idMatrix(5).println();
idMatrix(5).pump(Console.println);</
{{out}}
<pre>
Line 4,118 ⟶ 4,399:
=={{header|ZX Spectrum Basic}}==
{{trans|Applesoft_BASIC}}
<
20 GO SUB 200: REM Identity matrix
30 FOR r=1 TO size
Line 4,133 ⟶ 4,414:
240 LET i(i,i)=1
250 NEXT i
260 RETURN</
|