Identity matrix
You are encouraged to solve this task according to the task description, using any language you may know.
Build an identity matrix of a size known at runtime.
An identity matrix is a square matrix, of size n × n, where the diagonal elements are all 1s, and the other elements are all 0s.
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. <lang Ada>-- As prototyped in the Generic_Real_Arrays specification: -- function Unit_Matrix (Order : Positive; First_1, First_2 : Integer := 1) return Real_Matrix; -- For the task: mat : Real_Matrix := Unit_Matrix(5);</lang> For prior versions of Ada, or non floating point types its back to basics: <lang Ada>type Matrix is array(Positive Range <>, Positive Range <>) of Integer; mat : Matrix(1..5,1..5) := (others => (others => 0)); -- then after the declarative section: for i in mat'Range(1) loop mat(i,i) := 1; end loop;</lang>
ALGOL 68
Note: The generic vector and matrix code should be moved to a more generic page.
File: prelude/vector_base.a68<lang algol68>#!/usr/bin/a68g --script #
- -*- coding: utf-8 -*- #
- Define some generic vector initialisation and printing operations #
COMMENT REQUIRES:
MODE SCAL = ~ # a scalar, eg REAL #; FORMAT scal fmt := ~;
END COMMENT
INT vec lwb := 1, vec upb := 0; MODE VECNEW = [vec lwb:vec upb]SCAL; MODE VEC = REF VECNEW; FORMAT vec fmt := $"("n(vec upb-vec lwb)(f(scal fmt)", ")f(scal fmt)")"$;
PRIO INIT = 1;
OP INIT = (VEC self, SCAL scal)VEC: (
FOR col FROM LWB self TO UPB self DO self[col]:= scal OD; self
);
- ZEROINIT: defines the additive identity #
OP ZEROINIT = (VEC self)VEC:
self INIT SCAL(0);
OP REPR = (VEC self)STRING: (
FILE f; STRING s; associate(f,s); vec lwb := LWB self; vec upb := UPB self; putf(f, (vec fmt, self)); close(f); s
);
SKIP</lang>File: prelude/matrix_base.a68<lang algol68># -*- coding: utf-8 -*- #
- Define some generic matrix initialisation and printing operations #
COMMENT REQUIRES:
MODE SCAL = ~ # a scalar, eg REAL #; MODE VEC = []SCAL; FORMAT scal fmt := ~; et al.
END COMMENT
INT mat lwb := 1, mat upb := 0; MODE MATNEW = [mat lwb:mat upb, vec lwb: vec upb]SCAL; MODE MAT = REF MATNEW; FORMAT mat fmt = $"("n(vec upb-vec lwb)(f(vec fmt)","lx)f(vec fmt)")"l$;
PRIO DIAGINIT = 1;
OP INIT = (MAT self, SCAL scal)MAT: (
FOR row FROM LWB self TO UPB self DO self[row,] INIT scal OD; self
);
- ZEROINIT: defines the additive identity #
OP ZEROINIT = (MAT self)MAT:
self INIT SCAL(0);
OP REPR = (MATNEW self)STRING: (
FILE f; STRING s; associate(f,s); vec lwb := 2 LWB self; vec upb := 2 UPB self; mat lwb := LWB self; mat upb := UPB self; putf(f, (mat fmt, self)); close(f); s
);
OP DIAGINIT = (MAT self, VEC diag)MAT: (
ZEROINIT self; FOR d FROM LWB diag TO UPB diag DO self[d,d]:= diag[d] OD;
- or alternatively using TORRIX ...
DIAG self := diag;
self
);
- ONEINIT: defines the multiplicative identity #
OP ONEINIT = (MAT self)MAT: (
ZEROINIT self DIAGINIT (LOC[LWB self:UPB self]SCAL INIT SCAL(1))
- or alternatively using TORRIX ...
(DIAG out) VECINIT SCAL(1)
);
SKIP</lang>File: prelude/matrix_ident.a68<lang algol68># -*- coding: utf-8 -*- #
PRIO IDENT = 9; # The same as I for COMPLex #
OP IDENT = (INT lwb, upb)MATNEW:
ONEINIT LOC [lwb:upb,lwb:upb]SCAL;
OP IDENT = (INT upb)MATNEW: # default lwb is 1 #
1 IDENT upb;
SKIP</lang>File: prelude/matrix.a68<lang algol68>#!/usr/bin/a68g --script #
- -*- coding: utf-8 -*- #
PR READ "prelude/vector_base.a68" PR; PR READ "prelude/matrix_base.a68" PR; PR READ "prelude/matrix_ident.a68" PR;
SKIP</lang>File: test/matrix_ident.a68<lang algol68>#!/usr/bin/a68g --script #
- -*- coding: utf-8 -*- #
MODE SCAL = REAL; FORMAT scal fmt := $g(-3,1)$;
PR READ "prelude/matrix.a68" PR;
print(REPR IDENT 4)</lang>
- Output:
((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))
APL
Making an identity matrix in APL involves the outer product of the inequality function.
For a square matrix of 3: <lang apl>
∘.=⍨⍳3
1 0 0 0 1 0 0 0 1 </lang>
For a function that makes an identity matrix: <lang apl>
ID←{∘.=⍨⍳⍵} ID 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 </lang>
There is a more idomatic way however:
<lang apl>
ID←{⍵ ⍵ ρ 1, ⍵ρ0}
</lang>
Applesoft BASIC
<lang Applesoft BASIC> 100 INPUT "MATRIX SIZE:"; SIZE% 110 GOSUB 200"IDENTITYMATRIX 120 FOR R = 0 TO SIZE% 130 FOR C = 0 TO SIZE% 140 LET S$ = CHR$(13) 150 IF C < SIZE% THEN S$ = " " 160 PRINT IM(R, C) S$; : NEXT C, R 170 END
200 REMIDENTITYMATRIX SIZE% 210 LET SIZE% = SIZE% - 1 220 DIM IM(SIZE%, SIZE%) 230 FOR I = 0 TO SIZE% 240 LET IM(I, I) = 1 : NEXT I 250 RETURN :IM </lang>
ATS
<lang ATS> (* ****** ****** *) // // How to compile: // // patscc -DATS_MEMALLOC_LIBC -o idmatrix idmatrix.dats // (* ****** ****** *) //
- include
"share/atspre_staload.hats" // (* ****** ****** *)
extern fun idmatrix{n:nat}(n: size_t(n)): matrixref(int, n, n) implement idmatrix(n) = matrixref_tabulate_cloref<int> (n, n, lam(i, j) => bool2int0(i = j))
(* ****** ****** *)
implement main0 () = { // val N = 5 // val M = idmatrix(i2sz(N)) val () = fprint_matrixref_sep (stdout_ref, M, i2sz(N), i2sz(N), " ", "\n") val () = fprint_newline (stdout_ref) // } (* end of [main0] *) </lang>
AutoHotkey
<lang autohotkey>msgbox % Clipboard := I(6) return
I(n){
r := "--`n" , s := " " loop % n { k := A_index , r .= "| " loop % n r .= A_index=k ? "1, " : "0, " r := RTrim(r, " ,") , r .= " |`n" } loop % 4*n s .= " " return Rtrim(r,"`n") "`n" s "--"
}</lang>
- Output:
-- | 1, 0, 0, 0, 0, 0 | | 0, 1, 0, 0, 0, 0 | | 0, 0, 1, 0, 0, 0 | | 0, 0, 0, 1, 0, 0 | | 0, 0, 0, 0, 1, 0 | | 0, 0, 0, 0, 0, 1 | --
AWK
<lang AWK>
- syntax: GAWK -f IDENTITY_MATRIX.AWK size
BEGIN {
size = ARGV[1] if (size !~ /^[0-9]+$/) { print("size invalid or missing from command line") exit(1) } for (i=1; i<=size; i++) { for (j=1; j<=size; j++) { x = (i == j) ? 1 : 0 printf("%2d",x) # print arr[i,j] = x # build } printf("\n") } exit(0)
} </lang>
- Output:
for command
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
BBC BASIC
<lang bbcbasic> INPUT "Enter size of matrix: " size%
PROCidentitymatrix(size%, im()) FOR r% = 0 TO size%-1 FOR c% = 0 TO size%-1 PRINT im(r%, c%),; NEXT PRINT NEXT r% END DEF PROCidentitymatrix(s%, RETURN m()) LOCAL i% DIM m(s%-1, s%-1) FOR i% = 0 TO s%-1 m(i%,i%) = 1 NEXT ENDPROC</lang>
Burlesque
Neither very elegant nor short but it'll do
<lang burlesque> blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 </lang>
The example above uses strings to generate the identity matrix. If you need a matrix with real numbers (Integers) then use:
<lang burlesque> 6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e! </lang>
C
<lang C>
- include <stdlib.h>
- include <stdio.h>
int main(int argc, char** argv) {
if (argc < 2) { printf("usage: identitymatrix <number of rows>\n"); exit(EXIT_FAILURE); } signed int rowsize = atoi(argv[1]); if (rowsize < 0) { printf("Dimensions of matrix cannot be negative\n"); exit(EXIT_FAILURE); } volatile int numElements = rowsize * rowsize; if (numElements < rowsize) { printf("Squaring %d caused result to overflow to %d.\n", rowsize, numElements); abort(); } int** matrix = calloc(numElements, sizeof(int*)); if (!matrix) { printf("Failed to allocate %d elements of %d bytes each\n", numElements, sizeof(int*)); abort(); } for (unsigned int row = 0;row < rowsize;row++) { matrix[row] = calloc(numElements, sizeof(int)); if (!matrix[row]) { printf("Failed to allocate %d elements of %d bytes each\n", numElements, sizeof(int)); abort(); } matrix[row][row] = 1; } printf("Matrix is: \n"); for (unsigned int row = 0;row < rowsize;row++) { for (unsigned int column = 0;column < rowsize;column++) { printf("%d ", matrix[row][column]); } printf("\n"); }
} </lang>
C++
<lang cpp>template<class T> class matrix { public:
matrix( unsigned int nSize ) : m_oData(nSize * nSize, 0), m_nSize(nSize) {}
inline T& operator()(unsigned int x, unsigned int y) { return m_oData[x+m_nSize*y]; }
void identity() { int nCount = 0; int nStride = m_nSize + 1; std::generate( m_oData.begin(), m_oData.end(), [&]() { return !(nCount++%nStride); } ); }
inline unsigned int size() { return m_nSize; }
private:
std::vector<T> m_oData; unsigned int m_nSize;
};
int main() {
int nSize; std::cout << "Enter matrix size (N): "; std::cin >> nSize;
matrix<int> oMatrix( nSize );
oMatrix.identity();
for ( unsigned int y = 0; y < oMatrix.size(); y++ ) { for ( unsigned int x = 0; x < oMatrix.size(); x++ ) { std::cout << oMatrix(x,y) << " "; } std::cout << std::endl; } return 0;
} </lang>
<lang cpp>
- include <boost/numeric/ublas/matrix.hpp>
int main() {
using namespace boost::numeric::ublas; int nSize; std::cout << "Enter matrix size (N): "; std::cin >> nSize;
identity_matrix<int> oMatrix( nSize );
for ( unsigned int y = 0; y < oMatrix.size2(); y++ ) { for ( unsigned int x = 0; x < oMatrix.size1(); x++ ) { std::cout << oMatrix(x,y) << " "; } std::cout << std::endl; }
return 0;
} </lang>
- Output:
Enter matrix size (N): 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
C#
<lang csharp> using System; using System.Linq;
namespace IdentityMatrix {
class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Requires exactly one argument"); return; } int n; if (!int.TryParse(args[0], out n)) { Console.WriteLine("Requires integer parameter"); return; }
var identity = Enumerable.Range(0, n).Select(i => Enumerable.Repeat(0, n).Select((z,j) => j == i ? 1 : 0).ToList()).ToList(); foreach (var row in identity) { foreach (var elem in row) { Console.Write(" " + elem); } Console.WriteLine(); } Console.ReadKey(); } }
} </lang>
- Output:
1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1
Clojure
The (vec ) function in the following solution is with respect to vector matrices. If dealing with normal lists matrices (e.g. <lang clojure> '( (0 1) (2 3) ) </lang> , then care to remove the vec function. <lang clojure>(defn identity-matrix [n]
(let [row (conj (repeat (dec n) 0) 1)] (vec (for [i (range 1 (inc n))] (vec (reduce conj (drop i row ) (take i row)))))))
</lang>
- Output:
<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]] </lang>
The following is a more idomatic definition that utilizes infinite lists and cycling. <lang clojure> (defn identity-matrix [n]
(take n (partition n (dec n) (cycle (conj (repeat (dec n) 0) 1)))))
</lang>
Common Lisp
Common Lisp provides multi-dimensional arrays.
<lang lisp>(defun make-identity-matrix (n)
(let ((array (make-array (list n n) :initial-element 0))) (loop for i below n do (setf (aref array i i) 1)) array))
</lang>
- Output:
* (make-identity-matrix 5) #2A((1 0 0 0 0) (0 1 0 0 0) (0 0 1 0 0) (0 0 0 1 0) (0 0 0 0 1))
Component Pascal
BlackBox Component Builder <lang oberon2> MODULE Algebras; IMPORT StdLog,Strings;
TYPE Matrix = POINTER TO ARRAY OF ARRAY OF INTEGER;
PROCEDURE NewIdentityMatrix(n: INTEGER): Matrix; VAR m: Matrix; i: INTEGER; BEGIN NEW(m,n,n); FOR i := 0 TO n - 1 DO m[i,i] := 1; END; RETURN m; END NewIdentityMatrix;
PROCEDURE Show(m: Matrix); VAR i,j: INTEGER; BEGIN FOR i := 0 TO LEN(m,0) - 1 DO FOR j := 0 TO LEN(m,1) - 1 DO StdLog.Int(m[i,j]); END; StdLog.Ln END END Show;
PROCEDURE Do*;
BEGIN
Show(NewIdentityMatrix(5));
END Do;
END Algebras.
</lang>
Execute: ^Q Algebras.Do
- Output:
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
D
<lang d>import std.traits;
T[][] matId(T)(in size_t n) pure nothrow if (isAssignable!(T, T)) {
auto Id = new T[][](n, n);
foreach (r, row; Id) { static if (__traits(compiles, {row[] = 0;})) { row[] = 0; // vector op doesn't work with T = BigInt row[r] = 1; } else { foreach (c; 0 .. n) row[c] = (c == r) ? 1 : 0; } }
return Id;
}
void main() {
import std.stdio, std.bigint; enum form = "[%([%(%s, %)],\n %)]]";
immutable id1 = matId!real(5); writefln(form ~ "\n", id1);
immutable id2 = matId!BigInt(3); writefln(form ~ "\n", id2);
// auto id3 = matId!(const int)(2); // cant't compile
}</lang>
- Output:
[[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, 1, 0], [0, 0, 1]]
Delphi
<lang Delphi>program IdentityMatrix;
// Modified from the Pascal version
{$APPTYPE CONSOLE}
var
matrix: array of array of integer; n, i, j: integer;
begin
write('Size of matrix: '); readln(n); setlength(matrix, n, n);
for i := 0 to n - 1 do matrix[i,i] := 1; for i := 0 to n - 1 do begin for j := 0 to n - 1 do write (matrix[i,j], ' '); writeln; end;
end.</lang>
- Output:
Size of matrix: 5 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
Eiffel
<lang Eiffel> class APPLICATION
inherit ARGUMENTS
create make
feature {NONE} -- Initialization
make -- Run application. local dim : INTEGER -- Dimension of the identity matrix do from dim := 1 until dim > 10 loop print_matrix( identity_matrix(dim) ) dim := dim + 1 io.new_line end
end
feature -- Access
identity_matrix(dim : INTEGER) : ARRAY2[REAL_64]
require dim > 0 local matrix : ARRAY2[REAL_64] i : INTEGER do
create matrix.make_filled (0.0, dim, dim) from i := 1 until i > dim loop matrix.put(1.0, i, i) i := i + 1 end
Result := matrix end
print_matrix(matrix : ARRAY2[REAL_64]) local i, j : INTEGER do from i := 1 until i > matrix.height loop print("[ ") from j := 1 until j > matrix.width loop print(matrix.item (i, j)) print(" ") j := j + 1 end print("]%N") i := i + 1 end end
end </lang>
- Output:
[ 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 ]
Elixir
<lang elixir>defmodule Matrix do
def identity(n) do Enum.map(0..n-1, fn i -> for j <- 0..n-1, do: (if i==j, do: 1, else: 0) end) end
end
IO.inspect Matrix.identity(5)</lang>
- Output:
[[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]]
Erlang
<lang erlang>%% Identity Matrix in Erlang for the Rosetta Code Wiki. %% Implemented by Arjun Sunel
-module(identity_matrix). -export([square_matrix/2 , identity/1]).
square_matrix(Size, Elements) ->
[[Elements(Column, Row) || Column <- lists:seq(1, Size)] || Row <- lists:seq(1, Size)].
identity(Size) ->
square_matrix(Size, fun(Column, Row) -> case Column of Row -> 1; _ -> 0 end end).</lang>
ERRE
<lang ERRE> PROGRAM IDENTITY
!$DYNAMIC DIM A[0,0]
BEGIN
PRINT(CHR$(12);) ! CLS INPUT("Matrix size",N%) !$DIM A[N%,N%] FOR I%=1 TO N% DO A[I%,I%]=1 END FOR
! print matrix
FOR I%=1 TO N% DO FOR J%=1 TO N% DO WRITE("###";A[I%,J%];) END FOR PRINT END FOR
END PROGRAM </lang>
Euler Math Toolbox
<lang Euler Math Toolbox> function IdentityMatrix(n)
$ X:=zeros(n,n); $ for i=1 to n $ X[i,i]:=1; $ end; $ return X; $endfunction
</lang>
<lang Euler Math Toobox> >function IdentityMatrix (n:index) $ return setdiag(zeros(n,n),0,1); $endfunction </lang>
<lang> >id(5) </lang>
F#
Builds a 2D matrix with the given square size. <lang FSharp> let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0) </lang>
- Output:
<lang FSharp> ident 10;; val it : int [,] = [[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]]
</lang>
Factor
USE: math.matrices IN: scratchpad 6 identity-matrix . { { 1 0 0 0 0 0 } { 0 1 0 0 0 0 } { 0 0 1 0 0 0 } { 0 0 0 1 0 0 } { 0 0 0 0 1 0 } { 0 0 0 0 0 1 } }
FBSL
FBSL's BASIC layer can easily manipulate square matrices of arbitrary sizes and data types in ways similar to e.g. BBC BASIC or OxygenBasic as shown elsewhere on this page. But FBSL has also an extremely fast built-in single-precision vector2f/3f/4f, plane4f, quaternion4f, and matrix4f math library totaling 150 functions and targeting primarily 3D rendering tasks:
#APPTYPE CONSOLE
TYPE M4F ' Matrix 4F
- m11 AS SINGLE
- m12 AS SINGLE
- m13 AS SINGLE
- m14 AS SINGLE
- m21 AS SINGLE
- m22 AS SINGLE
- m23 AS SINGLE
- m24 AS SINGLE
- m31 AS SINGLE
- m32 AS SINGLE
- m33 AS SINGLE
- m34 AS SINGLE
- m41 AS SINGLE
- m42 AS SINGLE
- m43 AS SINGLE
- m44 AS SINGLE
END TYPE
DIM m AS M4F ' DIM zeros out any variable automatically
PRINT "Matrix 'm' is identity: ", IIF(MATRIXISIDENTITY(@m), "TRUE", "FALSE") ' is matrix an identity?
MATRIXIDENTITY(@m) ' set matrix to identity
PRINT "Matrix 'm' is identity: ", IIF(MATRIXISIDENTITY(@m), "TRUE", "FALSE") ' is matrix an identity?
PAUSE
- Output:
Matrix 'm' is identity: FALSE
Matrix 'm' is identity: TRUE
Press any key to continue...
Fortran
<lang fortran> program identitymatrix
real, dimension(:, :), allocatable :: I character(len=8) :: fmt integer :: ms, j
ms = 10 ! the desired size
allocate(I(ms,ms)) I = 0 ! Initialize the array. forall(j = 1:ms) I(j,j) = 1 ! Set the diagonal.
! I is the identity matrix, let's show it:
write (fmt, '(A,I2,A)') '(', ms, 'F6.2)' ! if you consider to have used the (row, col) convention, ! the following will print the transposed matrix (col, row) ! but I' = I, so it's not important here write (*, fmt) I(:,:)
deallocate(I)
end program identitymatrix </lang>
Notorious trick
The objective is to do the assignment in one fell swoop, rather than separately setting the 0 values and the 1 values. It works because, with integer arithmetic, the only way that both i/j and j/i are one is when they are equal - thus one on the diagonal elements, and zero elsewhere because either i < j so that i/j = 0, or i > j so that j/i = 0. While this means two divides and a multiply per element instead of simply transferring a constant, the constraint on speed is likely to be the limited bandwidth from cpu to memory. The expression's code would surely fit in the cpu's internal memory, and registers would be used for the variables.
<lang Fortran>
Program Identity Integer N Parameter (N = 666) Real A(N,N) Integer i,j
ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i) END
</lang>
FunL
<lang funl>def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 )
println( identity(3) )</lang>
- Output:
((1, 0, 0), (0, 1, 0), (0, 0, 1))
GAP
<lang gap># Built-in IdentityMat(3);
- One can also specify the base ring
IdentityMat(3, Integers mod 10);</lang>
Go
Library gonum/matrix
The newest shiniest matrix library for Go. <lang go>package main
import (
"fmt"
"github.com/gonum/matrix/mat64"
)
func eye(n int) *mat64.Dense {
m := mat64.NewDense(n, n, nil) for i := 0; i < n; i++ { m.Set(i, i, 1) } return m
}
func main() {
fmt.Println(mat64.Formatted(eye(3)))
}</lang>
- Output:
⎡1 0 0⎤ ⎢0 1 0⎥ ⎣0 0 1⎦
Library go.matrix
A somewhat earlier matrix library for Go. <lang go>package main
import (
"fmt"
mat "github.com/skelterjohn/go.matrix"
)
func main() {
fmt.Println(mat.Eye(3))
}</lang>
- Output:
{1, 0, 0, 0, 1, 0, 0, 0, 1}
From scratch
Simplest: A matrix as a slice of slices, allocated separately. <lang go>package main
import "fmt"
func main() {
fmt.Println(I(3))
}
func I(n int) [][]float64 {
m := make([][]float64, n) for i := 0; i < n; i++ { a := make([]float64, n) a[i] = 1 m[i] = a } return m
}</lang>
- Output:
No special formatting method used.
[[1 0 0] [0 1 0] [0 0 1]]
2D, resliced: Representation as a slice of slices still, but with all elements based on single underlying slice. Might save a little memory management, might have a little better locality. <lang go>package main
import "fmt"
func main() {
fmt.Println(I(3))
}
func I(n int) [][]float64 {
m := make([][]float64, n) a := make([]float64, n*n) for i := 0; i < n; i++ { a[i] = 1 m[i] = a[:n] a = a[n:] } return m
}</lang>
- Output:
Same as previous.
Flat: Representation as a single flat slice. You just have to know to handle it as a square matrix. In many cases that's not a problem and the code is simpler this way. If you want to add a little bit of type checking, you can define a matrix type as shown here. <lang go>package main
import "fmt"
type matrix []float64
func main() {
n := 3 m := I(n) // dump flat represenation fmt.Println(m)
// function x turns a row and column into an index into the // flat representation. x := func(r, c int) int { return r*n + c }
// access m by row and column. for r := 0; r < n; r++ { for c := 0; c < n; c++ { fmt.Print(m[x(r, c)], " ") } fmt.Println() }
}
func I(n int) matrix {
m := make(matrix, n*n) // a fast way to initialize the flat representation n++ for i := 0; i < len(m); i += n { m[i] = 1 } return m
}</lang>
- Output:
[1 0 0 0 1 0 0 0 1] 1 0 0 0 1 0 0 0 1
Groovy
Solution: <lang groovy>def makeIdentityMatrix = { n ->
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }
}</lang>
Test: <lang groovy>(2..6).each { order ->
def iMatrix = makeIdentityMatrix(order) iMatrix.each { println it } println()
}</lang>
- Output:
[1, 0] [0, 1] [1, 0, 0] [0, 1, 0] [0, 0, 1] [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1] [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] [0, 1, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0] [0, 0, 0, 1, 0, 0] [0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 1]
Haskell
<lang haskell>matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]</lang> And a function to show matrix pretty: <lang haskell>showMat :: Int -> String showMat = unlines . map (unwords . map show)</lang>
<lang haskell>*Main> putStr $ showMat $ matId 9
1 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0
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
</lang>
Icon and Unicon
This code works for Icon and Unicon. <lang unicon>link matrix procedure main(argv)
if not (integer(argv[1]) > 0) then stop("Argument must be a positive integer.") matrix1 := identity_matrix(argv[1], argv[1]) write_matrix(&output,matrix1)
end </lang>
- Output:
->im 6 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 ->
J
<lang j> = i. 4 NB. create an Identity matrix of size 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
makeI=: =@i. NB. define as a verb with a user-defined name makeI 5 NB. create an Identity matrix of size 5
1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1</lang>
Java
<lang Java> public class IdentityMatrix {
public static int[][] matrix(int n){ int[][] array = new int[n][n];
for(int row=0; row<n; row++){ for(int col=0; col<n; col++){ if(row == col){ array[row][col] = 1; } else{ array[row][col] = 0; } } } return array; } public static void printMatrix(int[][] array){ for(int row=0; row<array.length; row++){ for(int col=0; col<array[row].length; col++){ System.out.print(array[row][col] + "\t"); } System.out.println(); } } public static void main (String []args){ printMatrix(matrix(5)); } } By Sani Yusuf @saniyusuf. </lang>
- Output:
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
JavaScript
<lang Javascript>function im(n) {
return Array.apply(null, new Array(n)).map(function(x, i, a) { return a.map(function(y, k) { return i === k ? 1 : 0; }) });
}</lang>
jq
Construction
<lang jq>def identity(n):
[range(0;n) | 0] as $row | reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );</lang>
Example: <lang jq>identity(4)</lang>produces:
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
Using matrix/2
Using the definition of matrix/2 at Create_a_two-dimensional_array_at_runtime#jq: <lang jq>def identity(n):
reduce range(0;n) as $i (0 | matrix(n;n); .[$i][$i] = 1);
</lang>
Julia
The eye function takes an integer argument and returns a square identity matrix of that size. <lang Julia> eye(3) </lang> This returns:
3x3 Float64 Array: 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0
If you want to take the size from the commandline: <lang Julia> eye(int(readline(STDIN))) </lang>
You can also can also call eye(m,n) to create an M-by-N identity matrix. For example: <lang Julia> eye(2,3) </lang> results in:
2x3 Float64 Array: 1.0 0.0 0.0 0.0 1.0 0.0
LSL
To test it yourself; rez a box on the ground, and add the following as a New Script. <lang LSL>default { state_entry() { llListen(PUBLIC_CHANNEL, "", llGetOwner(), ""); llOwnerSay("Please Enter a Dimension for an Identity Matrix."); } listen(integer iChannel, string sName, key kId, string sMessage) { llOwnerSay("You entered "+sMessage+"."); list lMatrix = []; integer x = 0; integer n = (integer)sMessage; for(x=0 ; x<n*n ; x++) { lMatrix += [(integer)(((x+1)%(n+1))==1)]; } //llOwnerSay("["+llList2CSV(lMatrix)+"]"); for(x=0 ; x<n ; x++) { llOwnerSay("["+llList2CSV(llList2ListStrided(lMatrix, x*n, (x+1)*n-1, 1))+"]"); } } }</lang>
- Output:
You: 0 Identity_Matrix: You entered 0. You: 1 Identity_Matrix: You entered 1. Identity_Matrix: [1] You: 3 Identity_Matrix: You entered 3. Identity_Matrix: [1, 0, 0] Identity_Matrix: [0, 1, 0] Identity_Matrix: [0, 0, 1] You: 5 Identity_Matrix: You entered 5. Identity_Matrix: [1, 0, 0, 0, 0] Identity_Matrix: [0, 1, 0, 0, 0] Identity_Matrix: [0, 0, 1, 0, 0] Identity_Matrix: [0, 0, 0, 1, 0] Identity_Matrix: [0, 0, 0, 0, 1]
Lang5
<lang lang5>: identity-matrix
dup iota 'A set
: i.(*) A in ; [1] swap append reverse A swap reshape 'i. apply ;
5 identity-matrix .</lang>
- Output:
[ [ 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 ] ]
LFE
<lang lisp> (defun identity
((`(,m ,n)) (identity m n)) ((m) (identity m m)))
(defun identity (m n)
(lists:duplicate m (lists:duplicate n 1)))
</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:
<lang lisp> > (identity 3) ((1 1 1) (1 1 1) (1 1 1)) > (identity 3 3) ((1 1 1) (1 1 1) (1 1 1)) > (identity '(3 3)) ((1 1 1) (1 1 1) (1 1 1))
</lang>
Lua
<lang lua> function identity_matrix (size)
local m = {} for i = 1, size do m[i] = {} for j = 1, size do m[i][j] = i == j and 1 or 0 end end return m
end
function print_matrix (m)
for i = 1, #m do print(table.concat(m[i], " ")) end
end
print_matrix(identity_matrix(5))</lang>
- Output:
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
Maple
One of a number of ways to do this: <lang Maple> > LinearAlgebra:-IdentityMatrix( 4 );
[1 0 0 0] [ ] [0 1 0 0] [ ] [0 0 1 0] [ ] [0 0 0 1]
</lang> Here, for instance, is another, in which the entries are (4-byte) floats. <lang Maple> > Matrix( 4, shape = scalar[1], datatype = float[4] );
[1. 0. 0. 0.] [ ] [0. 1. 0. 0.] [ ] [0. 0. 1. 0.] [ ] [0. 0. 0. 1.]
</lang> Yet another, with 2-byte integer entries: <lang Maple> > Matrix( 4, shape = identity, datatype = integer[ 2 ] );
[1 0 0 0] [ ] [0 1 0 0] [ ] [0 0 1 0] [ ] [0 0 0 1]
</lang>
Mathematica
<lang Mathematica>IdentityMatrix[4]</lang>
MATLAB / Octave
The eye function create the identity (I) matrix, e.g.:
<lang MATLAB>I = eye(10)</lang>
Maxima
<lang maxima>ident(4); /* matrix([1, 0, 0, 0],
[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]) */</lang>
NetRexx
Using int Array
<lang NetRexx>/* NetRexx ************************************************************
- show identity matrix of size n
- I consider m[i,j] to represent the matrix
- 09.07.2013 Walter Pachl (translated from REXX Version 2)
- /
options replace format comments java crossref symbols binary
Parse Arg n . If n= then n=5 Say 'Identity Matrix of size' n '(m[i,j] IS the Matrix)' m=int[n,n] -- Allocate 2D square array at run-time Loop i=0 To n-1 -- Like Java, arrays in NetRexx start at 0
ol= Loop j=0 To n-1 m[i,j]=(i=j) ol=ol m[i,j] End Say ol End
</lang>
Using Indexed String
<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols nobinary
runSample(arg) return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method createIdMatrix(n) public static
DIM_ = 'DIMENSION' m = 0 -- Indexed string to hold matrix; default value for all elements is zero m[DIM_] = n loop i = 1 to n -- NetRexx indexed strings don't have to start at zero m[i, i] = 1 -- set this diagonal element to 1 end i return m
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method displayIdMatrix(m) public static
DIM_ = 'DIMENSION' if \m.exists(DIM_) then signal RuntimeException('Matrix dimension not set') n = m[DIM_] loop i = 1 to n ol = loop j = 1 To n ol = ol m[i, j] end j say ol end i return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) public static
parse arg n . if n = then n = 5 say 'Identity Matrix of size' n displayIdMatrix(createIdMatrix(n)) return
</lang>
Nim
<lang nim>proc identityMatrix(n): auto =
result = newSeq[seq[int]](n) for i in 0 .. < result.len: result[i] = newSeq[int](n) result[i][i] = 1</lang>
Objeck
<lang objeck>class IdentityMatrix {
function : Matrix(n : Int) ~ Int[,] { array := Int->New[n,n]; for(row:=0; row<n; row+=1;){ for(col:=0; col<n; col+=1;){ if(row = col){ array[row, col] := 1; } else{ array[row,col] := 0; }; }; }; return array; } function : PrintMatrix(array : Int[,]) ~ Nil { sizes := array->Size(); for(row:=0; row<sizes[0]; row+=1;){ for(col:=0; col<sizes[1]; col+=1;){ value := array[row,col]; "{$value} \t"->Print(); }; '\n'->PrintLine(); }; } function : Main(args : String[]) ~ Nil { PrintMatrix(Matrix(5)); }
} </lang>
OCaml
From the interactive loop (that we call the "toplevel"):
<lang ocaml>$ ocaml
- let make_id_matrix n =
let m = Array.make_matrix n n 0.0 in for i = 0 to pred n do m.(i).(i) <- 1.0 done; (m) ;;
val make_id_matrix : int -> float array array = <fun>
- make_id_matrix 4 ;;
- : float array array = [| [|1.; 0.; 0.; 0.|];
[|0.; 1.; 0.; 0.|]; [|0.; 0.; 1.; 0.|]; [|0.; 0.; 0.; 1.|] |]</lang>
another way:
<lang ocaml># let make_id_matrix n =
Array.init n (fun i -> Array.init n (fun j -> if i = j then 1.0 else 0.0)) ;;
val make_id_matrix : int -> float array array = <fun>
- make_id_matrix 4 ;;
- : float array array = [| [|1.; 0.; 0.; 0.|];
[|0.; 1.; 0.; 0.|]; [|0.; 0.; 1.; 0.|]; [|0.; 0.; 0.; 1.|] |]</lang>
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.
Octave
The eye function create the identity (I) matrix, e.g.:
<lang octave>I = eye(10)</lang>
ooRexx
ooRexx doesn't have a proper matrix class, but it does have multidimensional arrays. <lang ooRexx> say "a 3x3 identity matrix" say call printMatrix createIdentityMatrix(3) say say "a 5x5 identity matrix" say call printMatrix createIdentityMatrix(5)
- routine createIdentityMatrix
use arg size matrix = .array~new(size, size) loop i = 1 to size loop j = 1 to size if i == j then matrix[i, j] = 1 else matrix[i, j] = 0 end j end i return matrix
- routine printMatrix
use arg matrix
loop i = 1 to matrix~dimension(1) line = "" loop j = 1 to matrix~dimension(2) line = line matrix[i, j] end j say line end i
</lang>
- Output:
a 3x3 identity matrix 1 0 0 0 1 0 0 0 1 a 5x5 identity 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
OxygenBasic
<lang oxygenbasic> Class SquareMatrix '=================
double *Cell sys size
method SetIdentity() indexbase 0 sys e,i,j e=size*size for i=0 to <size cell(i*size+j)=1 : j++ next end method
method constructor(sys n) @cell=getmemory n*n*sizeof double size=n end method
method destructor() freememory @cell end method
end class
new SquareMatrix M(8) M.SetIdentity '... del M </lang>
Pascal
<lang pascal>program IdentityMatrix(input, output);
var
matrix: array of array of integer; n, i, j: integer;
begin
write('Size of matrix: '); readln(n); setlength(matrix, n, n);
for i := 0 to n - 1 do matrix[i,i] := 1; for i := 0 to n - 1 do begin for j := 0 to n - 1 do write (matrix[i,j], ' '); writeln; end;
end.</lang>
- Output:
% ./IdentityMatrix Size of matrix: 5 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
PARI/GP
Built-in: <lang parigp>matid(9)</lang>
Custom: <lang parigp>matrix(9,9,i,j,i==j)</lang>
Perl
<lang perl>sub identity_matrix {
my $n = shift; map { my $i = $_; [ map { ($_ == $i) - 0 } 1 .. $n ] } 1 .. $n;
}
@ARGV = (4, 5, 6) unless @ARGV;
for (@ARGV) {
my @id = identity_matrix $_; print "$_:\n"; for (my $i=0; $i<@id; ++$i) { print join ' ', @{$id[$i]}, "\n"; } print "\n";
} </lang>
- Output:
4: 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 5: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 6: 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1
Perl 6
<lang perl6>sub identity-matrix($n) {
my @id; for flat ^$n X ^$n -> $i, $j { @id[$i][$j] = +($i == $j); } @id;
}
.say for identity-matrix(5);</lang>
- Output:
[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]
On the other hand, this may be clearer and/or faster: <lang perl6>sub identity-matrix($n) {
my @id = [0 xx $n] xx $n; @id[$_][$_] = 1 for ^$n; @id;
}</lang>
Here is yet an other way to do it: <lang perl6>sub identity-matrix($n) {
([1, |(0 xx $n-1)].item, *.rotate(-1).item ... *)[^$n]
}</lang>
PHP
<lang php> function createMatrix($size) {
$result = array();
for ($i = 0; $i < $size; $i++) { $row = array_fill(0, $size, 0); $row[$i] = 1; $result[] = $row; }
return $result;
}
function printMatrix(array $matrix) {
foreach ($matrix as $row) { foreach ($row as $column) { echo $column . " "; } echo PHP_EOL; } echo PHP_EOL;
}
printMatrix(createMatrix(5)); </lang>
- Output:
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
PicoLisp
<lang PicoLisp>(de identity (Size)
(let L (need Size (1) 0) (make (do Size (link (copy (rot L))) ) ) ) )</lang>
Test: <lang PicoLisp>: (identity 3) -> ((1 0 0) (0 1 0) (0 0 1))
- (mapc println (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)</lang>
PL/I
<lang PL/I> identity: procedure (A, n);
declare A(n,n) fixed controlled; declare (i,n) fixed binary; allocate A; A = 0; do i = 1 to n; A(i,i) = 1; end;
end identity; </lang>
PostScript
<lang PostScript> % n ident [identity-matrix] % create an identity matrix of dimension n*n. % Uses a local dictionary for its one parameter, perhaps overkill. % Constructs arrays of arrays of integers using [], for loops, and stack manipulation. /ident { 1 dict begin /n exch def
[ 1 1 n { % [ i [ exch % [ [ i 1 1 n { % [ [ i j 1 index eq { 1 }{ 0 } ifelse % [ [ i b exch % [ [ b i } for % [ [ b+ i pop ] % [ [ b+ ] } for % [ [b+]+ ] ]
end } def </lang>
PowerShell
<lang PowerShell> function id($n) {
if($n -gt 0) { $array = @(1..$n | foreach{ @(0) }) 0..($n-1) | foreach{ $i = $_ $array[$i] = @(switch(0..($n-1)){ $i {1} default {0} }) } $array } else { @() }
} function show($a) {
if($a.Count -gt 0) { $n = $a.Count - 1 0..$n | foreach{ "$($a[$_][0..$n])" } }
} $array = id 4 show $array </lang> Output:
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
<lang PowerShell> $array[0][0] $array[0][1] </lang> Output:
1 0
PureBasic
<lang purebasic>>Procedure identityMatrix(Array i(2), size) ;valid only for size >= 0
;formats array i() as an identity matrix of size x size Dim i(size - 1, size - 1)
Protected j For j = 0 To size - 1 i(j, j) = 1 Next
EndProcedure
Procedure displayMatrix(Array a(2))
Protected rows = ArraySize(a(), 2), columns = ArraySize(a(), 1) Protected i, j For i = 0 To rows For j = 0 To columns Print(RSet(Str(a(i, j)), 3, " ")) Next PrintN("") Next
EndProcedure
If OpenConsole()
Dim i3(0, 0) Dim i4(0, 0) identityMatrix(i3(), 3) identityMatrix(i4(), 4) displayMatrix(i3()) PrintN("") displayMatrix(i4()) Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole()
EndIf</lang>
- Output:
1 0 0 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
Python
Python: Nested lists as matrix
A simple solution, using nested lists to represent the matrix. <lang python>def identity(size):
matrix = [[0]*size for i in range(size)] #matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists
for i in range(size): matrix[i][i] = 1 for rows in matrix: for elements in rows: print elements, print ""</lang>
Python: Matrix using dict of points
A dict of tuples of two ints (x, y) are used to represent the matrix. <lang python>>>> def identity(size): ... return {(x, y):int(x == y) for x in range(size) for y in range(size)} ... >>> size = 4 >>> matrix = identity(size) >>> print('\n'.join(' '.join(str(matrix[(x, y)]) for x in range(size)) for y in range(size))) 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 >>> </lang>
Python: Matrix from numpy
A solution using the numpy library <lang python> np.mat(np.eye(size)) </lang>
R
When passed a single scalar argument, diag
produces an identity matrix of size given by the scalar. For example:
<lang rsplus>diag(3)</lang>
produces:
[,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1
Racket
<lang racket>
- lang racket
(require math) (identity-matrix 5) </lang>
- Output:
(array #[#[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]])
REXX
version 1
The REXX language doesn't have matrixes as such, so the problem is largely how to display the "matrix".
The code to display the matrices was kept as a stand-alone general-purpose (square) matrix display subroutine,
which, in part, finds the maximum widths of the integer and decimal fraction parts (if any) and uses them to
align (right-justify according to the [possibly implied] decimal point) the columns of the square matrix.
<lang rexx>/*REXX program creates and displays any sized identity matrix. */
do k=3 to 6 /* [↓] build & display a matrix.*/ call identity_matrix k /*build and display a kxk matrix.*/ end /*k*/ /* [↑] use general─purpose disp.*/
exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────IDENTITY_MATRIX subroutine──────────*/ identity_matrix: procedure; parse arg n; $=
do r=1 for n /*build identity matrix, by row,*/ do c=1 for n /* ··· and by col.*/ $=$ (r==c) /*append zero or one (if on diag)*/ end /*c*/ end /*r*/
call showMatrix 'identity matrix of size' n, $ return /*──────────────────────────────────SHOWMATRIX subroutine───────────────*/ showMatrix: procedure; parse arg hdr,x; #=words(x) /*#: # of elements*/ dp=0 /*DP: dec fraction width.*/ w=0 /*W: integer part width.*/
do n=1 until n*n>=#; _=word(x,n) /*find matrix order (size).*/ parse var _ y '.' f; w=max(w, length(y)); dp=max(dp, length(f)) end /*n*/ /* [↑] idiomatically find widths to align output*/
w=w+1 say; say center(hdr, max(length(hdr)+6, (w+1)*#%n), '─'); say
- =0 /*#: element #*/
do row=1 for n; _=left(,n+w) /*indentation.*/ do col=1 for n; #=#+1 /*bump element*/ _=_ right(format(word(x, #), , dp)/1, w) end /*col*/ /* [↑] division by 1 normalizes #*/ say _ /*display one line of the matrix. */ end /*row*/
return</lang>
- Output:
using the default sizes (3 ──► 6) for generating four matrices
───identity matrix of size 3─── 1 0 0 0 1 0 0 0 1 ───identity matrix of size 4─── 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ───identity matrix of size 5─── 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 ───identity matrix of size 6─── 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1
version 2
An alternative?! <lang rexx> /* REXX ***************************************************************
- show identity matrix of size n
- I consider m.i.j to represent the matrix (not needed for showing)
- 06.07.2012 Walter Pachl
- /
Parse Arg n Say 'Identity Matrix of size' n '(m.i.j IS the Matrix)' m.=0 Do i=1 To n
ol= Do j=1 To n m.i.j=(i=j) ol=olformat(m.i.j,2) /* or ol=ol (i=j) */ End Say ol End
</lang>
- Output:
Identity Matrix of size 3 (m.i.j IS the Matrix) 1 0 0 0 1 0 0 0 1
This could be a 3-dimensional sparse matrix with one element set: <lang rexx> m.=0 m.0=1000 /* the matrix' size */ m.4.17.333='Walter' </lang>
Ruby
Using Array
<lang ruby>def identity(size)
Array.new(size){|i| Array.new(size){|j| i==j ? 1 : 0}}
end
[4,5,6].each do |size|
puts size, identity(size).map {|r| r.to_s}, ""
end</lang>
- Output:
4 [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1] 5 [1, 0, 0, 0, 0] [0, 1, 0, 0, 0] [0, 0, 1, 0, 0] [0, 0, 0, 1, 0] [0, 0, 0, 0, 1] 6 [1, 0, 0, 0, 0, 0] [0, 1, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0] [0, 0, 0, 1, 0, 0] [0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 1]
Using Matrix
<lang ruby> 2.1.1 :001 > require "matrix"
=> true
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]]
</lang>
Run BASIC
<lang runbasic>' formats array im() of size ims for ims = 4 to 6
print :print "--- Size: ";ims;" ---"
Dim im(ims,ims)
For i = 1 To ims im(i,i) = 1 next
For row = 1 To ims print "["; cma$ = "" For col = 1 To ims print cma$;im(row, col); cma$ = ", " next print "]" next
next ims</lang>
- Output:
--- Size: 4 --- [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1] --- Size: 5 --- [1, 0, 0, 0, 0] [0, 1, 0, 0, 0] [0, 0, 1, 0, 0] [0, 0, 0, 1, 0] [0, 0, 0, 0, 1] --- Size: 6 --- [1, 0, 0, 0, 0, 0] [0, 1, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0] [0, 0, 0, 1, 0, 0] [0, 0, 0, 0, 1, 0] [0, 0, 0, 0, 0, 1]
Scala
<lang scala>def identityMatrix(n:Int)=Array.tabulate(n,n)((x,y) => if(x==y) 1 else 0) def printMatrix[T](m:Array[Array[T]])=m map (_.mkString("[", ", ", "]")) mkString "\n"
printMatrix(identityMatrix(5))</lang>
- Output:
[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]
Scheme
When representing a matrix as a collection of nested lists: <lang scheme> (define (identity n)
(letrec ((uvec
(lambda (m i acc) (if (= i n) acc (uvec m (+ i 1) (cons (if (= i m) 1 0) acc)))))
(idgen
(lambda (i acc) (if (= i n) acc (idgen (+ i 1) (cons (uvec i 0 '()) acc))))))
(idgen 0 '())))
</lang> Test program: <lang scheme> (display (identity 4)) </lang>
- Output:
((1 0 0 0) (0 1 0 0) (0 0 1 0) (0 0 0 1))
Seed7
<lang seed7>$ include "seed7_05.s7i";
const type: matrix is array array integer;
const func matrix: identity (in integer: size) is func
result var matrix: identity is matrix.value; local var integer: index is 0; begin identity := size times size times 0; for index range 1 to size do identity[index][index] := 1; end for; end func;
const proc: writeMat (in matrix: a) is func
local var integer: i is 0; var integer: num is 0; begin for key i range a do for num range a[i] do write(num lpad 2); end for; writeln; end for; end func;
const proc: main is func
begin writeMat(identity(6)); end func;</lang>
- Output:
1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1
Sidef
<lang ruby>func identity_matrix(n) {
1..n -> map { |i| 1..n -> map {|j| j == i ? 1 : 0 } }
}
ARGV.len? ? ARGV.map {.to_i} : [4, 5, 6] -> each { |n|
say "\n#{n}:"; identity_matrix(n).each { |row| say row.join(' '); };
}</lang>
Sparkling
<lang sparkling>function unitMatrix(n) { return map(range(n), function(k1, v1) { return map(range(n), function(k2, v2) { return v2 == v1 ? 1 : 0; }); }); }</lang>
Tcl
When representing a matrix as a collection of nested lists: <lang tcl>proc I {rank {zero 0.0} {one 1.0}} {
set m [lrepeat $rank [lrepeat $rank $zero]] for {set i 0} {$i < $rank} {incr i} {
lset m $i $i $one
} return $m
}</lang> Or alternatively with the help of the tcllib package for rectangular data structures:
<lang tcl>package require struct::matrix
proc I {rank {zero 0.0} {one 1.0}} {
set m [struct::matrix] $m add columns $rank $m add rows $rank for {set i 0} {$i < $rank} {incr i} {
for {set j 0} {$j < $rank} {incr j} { $m set cell $i $j [expr {$i==$j ? $one : $zero}] }
} return $m
}</lang> Demonstrating the latter: <lang tcl>set m [I 5 0 1] ;# Integer 0/1 for clarity of presentation puts [$m format 2string]</lang>
- Output:
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
VBScript
<lang vb> build_matrix(7)
Sub build_matrix(n) Dim matrix() ReDim matrix(n-1,n-1) i = 0 'populate the matrix For row = 0 To n-1 For col = 0 To n-1 If col = i Then matrix(row,col) = 1 Else matrix(row,col) = 0 End If Next i = i + 1 Next 'display the matrix For row = 0 To n-1 For col = 0 To n-1 If col < n-1 Then WScript.StdOut.Write matrix(row,col) & " " Else WScript.StdOut.Write matrix(row,col) End If Next WScript.StdOut.WriteLine Next End Sub </lang>
- Output:
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
Wortel
<lang wortel>@let {
im ^(%^\@table ^(@+ =) @to)
!im 4
}</lang> Returns:
[[1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1]]
XPL0
<lang XPL0>include c:\cxpl\codes; def IntSize = 4; \number of bytes in an integer int Matrix, Size, I, J;
[Text(0, "Size: "); Size:= IntIn(0); Matrix:= Reserve(Size*IntSize); \reserve memory for 2D integer array for I:= 0 to Size-1 do
Matrix(I):= Reserve(Size*IntSize);
for J:= 0 to Size-1 do \make array an identity matrix
for I:= 0 to Size-1 do Matrix(I,J):= if I=J then 1 else 0;
for J:= 0 to Size-1 do \display the result
[for I:= 0 to Size-1 do [IntOut(0, Matrix(I,J)); ChOut(0, ^ )]; CrLf(0); ];
]</lang>
- Output:
Size: 5 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
zkl
Using lists of lists: <lang zkl>fcn idMatrix(n){
m:=(0).pump(n,List.createLong(n).write,0)*n; m.apply2(fcn(row,rc){ row[rc.inc()]=1 },Ref(0)); m
} idMatrix(5).println(); idMatrix(5).pump(Console.println);</lang>
- Output:
L(L(1,0,0,0,0),L(0,1,0,0,0),L(0,0,1,0,0),L(0,0,0,1,0),L(0,0,0,0,1)) L(1,0,0,0,0) L(0,1,0,0,0) L(0,0,1,0,0) L(0,0,0,1,0) L(0,0,0,0,1)
- Programming Tasks
- Solutions by Programming Task
- Matrices
- Ada
- ALGOL 68
- APL
- Applesoft BASIC
- ATS
- AutoHotkey
- AWK
- BBC BASIC
- Burlesque
- C
- C++
- STL
- Boost
- C sharp
- Clojure
- Common Lisp
- Component Pascal
- D
- Delphi
- Eiffel
- Elixir
- Erlang
- ERRE
- Euler Math Toolbox
- F Sharp
- Factor
- FBSL
- Fortran
- FunL
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- LSL
- Lang5
- LFE
- Lua
- Maple
- Mathematica
- MATLAB
- Octave
- Maxima
- NetRexx
- Nim
- Objeck
- OCaml
- OoRexx
- OxygenBasic
- Pascal
- PARI/GP
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- PostScript
- PowerShell
- PureBasic
- Python
- R
- Racket
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Seed7
- Sidef
- Sparkling
- Tcl
- Tcllib
- VBScript
- Wortel
- XPL0
- Zkl