Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,4 @@
---
category:
- Matrices
from: http://rosettacode.org/wiki/Identity_matrix

View file

@ -0,0 +1,24 @@
;Task:
Build an   [[wp:identity matrix|identity matrix]]   of a size known at run-time.
An ''identity matrix'' is a square matrix of size '''''n'' × ''n''''',
<br>where the diagonal elements are all '''1'''s (ones),
<br>and all the other elements are all '''0'''s (zeroes).
<math>I_n = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
0 & 0 & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & 1 \\
\end{bmatrix}</math>
;Related tasks:
* &nbsp; [[Spiral matrix]]
* &nbsp; [[Zig-zag matrix]]
* &nbsp; [[Ulam_spiral_(for_primes)]]
<br><br>

View file

@ -0,0 +1,8 @@
F identity_matrix(size)
V matrix = [[0] * size] * size
L(i) 0 .< size
matrix[i][i] = 1
R matrix
L(row) identity_matrix(3)
print(row)

View file

@ -0,0 +1,73 @@
* Identity matrix 31/03/2017
INDENMAT CSECT
USING INDENMAT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
L R1,N n
MH R1,N+2 n*n
SLA R1,2 *4
ST R1,LL amount of storage required
GETMAIN RU,LV=(R1) allocate storage for matrix
USING DYNA,R11 make storage addressable
LR R11,R1 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LA R7,1 j=1
DO WHILE=(C,R7,LE,N) do j=1 to n
IF CR,R6,EQ,R7 THEN if i=j then
LA R2,1 k=1
ELSE , else
LA R2,0 k=0
ENDIF , endif
LR R1,R6 i
BCTR R1,0 -1
MH R1,N+2 *n
AR R1,R7 (i-1)*n+j
BCTR R1,0 -1
SLA R1,2 *4
ST R2,A(R1) a(i,j)=k
LA R7,1(R7) j++
ENDDO , enddo j
LA R6,1(R6) i++
ENDDO , enddo i
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) do i=1 to n
LA R10,PG pgi=0
LA R7,1 j=1
DO WHILE=(C,R7,LE,N) do j=1 to n
LR R1,R6 i
BCTR R1,0 -1
MH R1,N+2 *n
AR R1,R7 (i-1)*n+j
BCTR R1,0 -1
SLA R1,2 *4
L R2,A(R1) a(i,j)
XDECO R2,XDEC edit
MVC 0(1,R10),XDEC+11 output
LA R10,1(R10) pgi+=1
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print
LA R6,1(R6) i++
ENDDO , enddo i
LA R1,A address to free
LA R2,LL amount of storage to free
FREEMAIN A=(R1),LV=(R2) free allocated storage
DROP R11 drop register
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
NN EQU 10 parameter n (90=>32K)
N DC A(NN) n
LL DS F n*n*4
PG DC CL(NN)' ' buffer
XDEC DS CL12 temp
DYNA DSECT
A DS F a(n,n)
YREGS
END INDENMAT

View file

@ -0,0 +1,33 @@
#!/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

View file

@ -0,0 +1,52 @@
# -*- 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

View file

@ -0,0 +1,11 @@
# -*- 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

View file

@ -0,0 +1,8 @@
#!/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

View file

@ -0,0 +1,9 @@
#!/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)

View file

@ -0,0 +1,22 @@
begin
% set m to an identity matrix of size s %
procedure makeIdentity( real array m ( *, * )
; integer value s
) ;
for i := 1 until s do begin
for j := 1 until s do m( i, j ) := 0.0;
m( i, i ) := 1.0
end makeIdentity ;
% test the makeIdentity procedure %
begin
real array id5( 1 :: 5, 1 :: 5 );
makeIdentity( id5, 5 );
r_format := "A"; r_w := 6; r_d := 1; % set output format for reals %
for i := 1 until 5 do begin
write();
for j := 1 until 5 do writeon( id5( i, j ) )
end for_i ;
end text
end.

View file

@ -0,0 +1,4 @@
.=3
1 0 0
0 1 0
0 0 1

View file

@ -0,0 +1,7 @@
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

View file

@ -0,0 +1,2 @@
ID.=
ID.=

View file

@ -0,0 +1 @@
ID{ ρ 1, ρ0}

View file

@ -0,0 +1,33 @@
(* ****** ****** *)
//
// 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] *)

View file

@ -0,0 +1,17 @@
# 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)
}

View file

@ -0,0 +1,58 @@
PROC CreateIdentityMatrix(BYTE ARRAY mat,BYTE size)
CARD pos
BYTE i,j
pos=0
FOR i=1 TO size
DO
FOR j=1 TO size
DO
IF i=j THEN
mat(pos)=1
ELSE
mat(pos)=0
FI
pos==+1
OD
OD
RETURN
PROC PrintMatrix(BYTE ARRAY mat,BYTE size)
CARD pos
BYTE i,j,v
pos=0
FOR i=1 TO size
DO
FOR j=1 TO size
DO
v=mat(pos)
IF j=size THEN
PrintF("%I%E",v)
ELSE
PrintF("%I ",v)
FI
pos==+1
OD
OD
RETURN
PROC Main()
BYTE size
BYTE ARRAY mat(400)
BYTE LMARGIN=$52,old
old=LMARGIN
LMARGIN=0 ;remove left margin on the screen
DO
Print("Get size of matrix [1-20] ")
size=InputB()
UNTIL size>=1 AND size<=20
OD
CreateIdentityMatrix(mat,size)
PrintMatrix(mat,size)
LMARGIN=old ;restore left margin on the screen
RETURN

View file

@ -0,0 +1,4 @@
-- 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);

View file

@ -0,0 +1,4 @@
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;

View file

@ -0,0 +1,108 @@
--------------------- IDENTITY MATRIX ----------------------
-- identityMatrix :: Int -> [(0|1)]
on identityMatrix(n)
set xs to enumFromTo(1, n)
script row
on |λ|(x)
script col
on |λ|(i)
if i = x then
1
else
0
end if
end |λ|
end script
map(col, xs)
end |λ|
end script
map(row, xs)
end identityMatrix
--------------------------- TEST ---------------------------
on run
unlines(map(showList, ¬
identityMatrix(5)))
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(", ", map(my str, xs)) & "]"
end showList
-- str :: a -> String
on str(x)
x as string
end str
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines

View file

@ -0,0 +1,17 @@
on indentityMatrix(n)
set digits to {}
set m to n - 1
repeat (n + m) times
set end of digits to 0
end repeat
set item n of digits to 1
set matrix to {}
repeat with i from n to 1 by -1
set end of matrix to items i thru (i + m) of digits
end repeat
return matrix
end indentityMatrix
return indentityMatrix(5)

View file

@ -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}}

View file

@ -0,0 +1,15 @@
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

View file

@ -0,0 +1,11 @@
identityM: function [n][
result: array.of: @[n n] 0
loop 0..dec n 'i -> result\[i]\[i]: 1
return result
]
loop 4..6 'sz [
print sz
loop identityM sz => print
print ""
]

View file

@ -0,0 +1,16 @@
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 "--"
}

View file

@ -0,0 +1,25 @@
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

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,7 @@
Using table
Eye =˜
•Show Eye 3
Using reshape
Eye1 {𝕩𝕩1𝕩0}
Eye1 5

View file

@ -0,0 +1,12 @@
1 0 0
0 1 0
0 0 1
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

View file

@ -0,0 +1,10 @@
beads 1 program 'Identity matrix'
var
id : array^2 of num
n = 5
calc main_init
loop from:1 to:n index:i
loop from:1 to:n index:j
id[i,j] = 1 if i == j else 0

View file

@ -0,0 +1,7 @@
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

View file

@ -0,0 +1 @@
6hd0bx#a.*\[#a.*0#a?dr@{(D!)\/1\/^^bx\/[+}m[e!

View file

@ -0,0 +1 @@
blsq ) 6 ^^^^10\/**XXcy\/co.+sp

View file

@ -0,0 +1,47 @@
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;
}

View file

@ -0,0 +1,23 @@
#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;
}

View file

@ -0,0 +1,35 @@
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();
}
}
}

View file

@ -0,0 +1,38 @@
#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);
}
int rowsize = atoi(argv[1]);
if (rowsize < 0) {
printf("Dimensions of matrix cannot be negative\n");
exit(EXIT_FAILURE);
}
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 %ld 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 %ld 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");
}
}

View file

@ -0,0 +1,6 @@
fn identity-matrix n:
[0:n] -> * fn i:
[0:n] -> * if = i: 1
else: 0
5 -> identity-matrix -> * print

View file

@ -0,0 +1 @@
'( (0 1) (2 3) )

View file

@ -0,0 +1,6 @@
(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)))))))

View file

@ -0,0 +1,2 @@
=> (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]]

View file

@ -0,0 +1,4 @@
(defn identity-matrix [n]
(take n
(partition n (dec n)
(cycle (conj (repeat (dec n) 0) 1)))))

View file

@ -0,0 +1,17 @@
100 INPUT "MATRIX SIZE:"; SIZE
110 GOSUB 200: REM IDENTITYMATRIX
120 FOR R = 0 TO SIZE
130 FOR C = 0 TO SIZE
140 S$ = CHR$(13)
150 IF C < SIZE THEN S$ = ""
160 PRINT MID$(STR$(IM(R, C)),1)S$;:REM MID$ STRIPS LEADING SPACES
170 NEXT C, R
180 END
190 REM *******************************
200 REM IDENTITYMATRIX SIZE%
210 SIZE = SIZE - 1
220 DIM IM(SIZE, SIZE)
230 FOR I = 0 TO SIZE
240 IM(I, I) = 1
250 NEXT I
260 RETURN

View file

@ -0,0 +1,4 @@
(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))

View file

@ -0,0 +1,5 @@
(defun identity-matrix (n)
(loop for a from 1 to n
collect (loop for e from 1 to n
if (= a e) collect 1
else collect 0)))

View file

@ -0,0 +1,35 @@
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.

View file

@ -0,0 +1,30 @@
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
}

View file

@ -0,0 +1,25 @@
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.

View file

@ -0,0 +1,20 @@
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

View file

@ -0,0 +1,61 @@
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

View file

@ -0,0 +1,14 @@
import extensions;
import system'routines;
import system'collections;
public program()
{
var n := console.write:"Enter the matrix size:".readLine().toInt();
var identity := new Range(0, n).selectBy:(i => new Range(0,n).selectBy:(j => (i == j).iif(1,0) ).summarize(new ArrayList()))
.summarize(new ArrayList());
identity.forEach:
(row) { console.printLine(row.asEnumerable()) }
}

View file

@ -0,0 +1,9 @@
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)

View file

@ -0,0 +1,11 @@
%% 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).

View file

@ -0,0 +1,7 @@
function IdentityMatrix(n)
$ X:=zeros(n,n);
$ for i=1 to n
$ X[i,i]:=1;
$ end;
$ return X;
$endfunction

View file

@ -0,0 +1,3 @@
>function IdentityMatrix (n:index)
$ return setdiag(zeros(n,n),0,1);
$endfunction

View file

@ -0,0 +1 @@
>id(5)

View file

@ -0,0 +1,13 @@
IDMATRIX
=LAMBDA(n,
LET(
ixs, SEQUENCE(n, n, 0, 1),
x, MOD(ixs, n),
y, QUOTIENT(ixs, n),
IF(x = y,
1,
0
)
)
)

View file

@ -0,0 +1 @@
let ident n = Array2D.init n n (fun i j -> if i = j then 1 else 0)

View file

@ -0,0 +1,11 @@
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]]

View file

@ -0,0 +1,3 @@
USING: math.matrices prettyprint ;
6 <identity-matrix> .

View file

@ -0,0 +1,4 @@
Func Identity(n)=Array id[n,n];[id]:=[1].
Identity(7)
[id]

View file

@ -0,0 +1,16 @@
S" fsl-util.fs" REQUIRED
: build-identity ( 'p n -- 'p ) \ make an NxN identity matrix
0 DO
I 1+ 0 DO
I J = IF 1.0E0 DUP I J }} F!
ELSE
0.0E0 DUP J I }} F!
0.0E0 DUP I J }} F!
THEN
LOOP
LOOP ;
6 6 float matrix a{{
a{{ 6 build-identity
6 6 a{{ }}fprint

View file

@ -0,0 +1,23 @@
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

View file

@ -0,0 +1,9 @@
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

View file

@ -0,0 +1,3 @@
DO 1 I = 1,N
DO 1 J = 1,N
1 A(I,J) = (I/J)*(J/I)

View file

@ -0,0 +1,32 @@
' FB 1.05.0 Win64
Dim As Integer n
Do
Input "Enter size of matrix "; n
Loop Until n > 0
Dim identity(1 To n, 1 To n) As Integer '' all zero by default
' enter 1s in diagonal elements
For i As Integer = 1 To n
identity(i, i) = 1
Next
' print identity matrix if n < 40
Print
If n < 40 Then
For i As Integer = 1 To n
For j As Integer = 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
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,2 @@
n = parseInt[input["Enter matrix dimension as an integer: "]]
println[formatMatrix[makeArray[[n, n], {|a,b| a==b ? 1 : 0}]]]

View file

@ -0,0 +1,3 @@
def identity( n ) = vector( n, n, \r, c -> if r == c then 1 else 0 )
println( identity(3) )

View file

@ -0,0 +1,24 @@
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

View file

@ -0,0 +1,5 @@
# Built-in
IdentityMat(3);
# One can also specify the base ring
IdentityMat(3, Integers mod 10);

View file

@ -0,0 +1,19 @@
package main
import (
"fmt"
"gonum.org/v1/gonum/mat"
)
func eye(n int) *mat.Dense {
m := mat.NewDense(n, n, nil)
for i := 0; i < n; i++ {
m.Set(i, i, 1)
}
return m
}
func main() {
fmt.Println(mat.Formatted(eye(3)))
}

View file

@ -0,0 +1,11 @@
package main
import (
"fmt"
mat "github.com/skelterjohn/go.matrix"
)
func main() {
fmt.Println(mat.Eye(3))
}

View file

@ -0,0 +1,17 @@
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
}

View file

@ -0,0 +1,18 @@
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
}

View file

@ -0,0 +1,34 @@
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
}

View file

@ -0,0 +1,3 @@
def makeIdentityMatrix = { n ->
(0..<n).collect { i -> (0..<n).collect { j -> (i == j) ? 1 : 0 } }
}

View file

@ -0,0 +1,5 @@
(2..6).each { order ->
def iMatrix = makeIdentityMatrix(order)
iMatrix.each { println it }
println()
}

View file

@ -0,0 +1 @@
matI n = [ [fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]

View file

@ -0,0 +1,2 @@
showMat :: [[Int]] -> String
showMat = unlines . map (unwords . map show)

View file

@ -0,0 +1,10 @@
*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

View file

@ -0,0 +1,4 @@
idMatrix :: Int -> [[Int]]
idMatrix n =
let xs = [1 .. n]
in xs >>= \x -> [xs >>= \y -> [fromEnum (x == y)]]

View file

@ -0,0 +1,7 @@
idMatrix :: Int -> [[Int]]
idMatrix n =
let xs = [1 .. n]
in (\x -> fromEnum . (x ==) <$> xs) <$> xs
main :: IO ()
main = (putStr . unlines) $ unwords . fmap show <$> idMatrix 5

View file

@ -0,0 +1,21 @@
100 PROGRAM "Identity.bas"
110 INPUT PROMPT "Enter size of matrix: ":N
120 NUMERIC A(1 TO N,1 TO N)
130 CALL INIT(A)
140 CALL WRITE(A)
150 DEF INIT(REF T)
160 FOR I=LBOUND(T,1) TO UBOUND(T,1)
170 FOR J=LBOUND(T,2) TO UBOUND(T,2)
180 LET T(I,J)=0
190 NEXT
200 LET T(I,I)=1
210 NEXT
220 END DEF
230 DEF WRITE(REF T)
240 FOR I=LBOUND(T,1) TO UBOUND(T,1)
250 FOR J=LBOUND(T,2) TO UBOUND(T,2)
260 PRINT T(I,J);
270 NEXT
280 PRINT
290 NEXT
300 END DEF

View file

@ -0,0 +1,6 @@
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

View file

@ -0,0 +1,12 @@
= 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

View file

@ -0,0 +1,13 @@
public class PrintIdentityMatrix {
public static void main(String[] args) {
int n = 5;
int[][] array = new int[n][n];
IntStream.range(0, n).forEach(i -> array[i][i] = 1);
Arrays.stream(array)
.map((int[] a) -> Arrays.toString(a))
.forEach(System.out::println);
}
}

View file

@ -0,0 +1,8 @@
function idMatrix(n) {
return Array.apply(null, new Array(n))
.map(function (x, i, xs) {
return xs.map(function (_, k) {
return i === k ? 1 : 0;
})
});
}

View file

@ -0,0 +1,16 @@
(() => {
// identityMatrix :: Int -> [[Int]]
const identityMatrix = n =>
Array.from({
length: n
}, (_, i) => Array.from({
length: n
}, (_, j) => i !== j ? 0 : 1));
// ----------------------- TEST ------------------------
return identityMatrix(5)
.map(JSON.stringify)
.join('\n');
})();

View file

@ -0,0 +1,3 @@
def identity(n):
[range(0;n) | 0] as $row
| reduce range(0;n) as $i ([]; . + [ $row | .[$i] = 1 ] );

View file

@ -0,0 +1 @@
identity(4)

View file

@ -0,0 +1,3 @@
def identity(n):
reduce range(0;n) as $i
(0 | matrix(n;n); .[$i][$i] = 1);

View file

@ -0,0 +1,33 @@
/* Identity matrix, in Jsish */
function identityMatrix(n) {
var mat = new Array(n).fill(0);
for (var r in mat) {
mat[r] = new Array(n).fill(0);
mat[r][r] = 1;
}
return mat;
}
provide('identityMatrix', 1);
if (Interp.conf('unitTest')) {
; identityMatrix(0);
; identityMatrix(1);
; identityMatrix(2);
; identityMatrix(3);
var mat = identityMatrix(4);
for (var r in mat) puts(mat[r]);
}
/*
=!EXPECTSTART!=
identityMatrix(0) ==> []
identityMatrix(1) ==> [ [ 1 ] ]
identityMatrix(2) ==> [ [ 1, 0 ], [ 0, 1 ] ]
identityMatrix(3) ==> [ [ 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 ]
=!EXPECTEND!=
*/

View file

@ -0,0 +1,2 @@
using LinearAlgebra
unitfloat64matrix = 1.0I

View file

@ -0,0 +1,3 @@
using LinearAlgebra
diagI3 = 1.0I(3)
fullI3 = collect(diagI3)

View file

@ -0,0 +1,5 @@
using LinearAlgebra
fullI3 = Matrix{Float64}(I, 3, 3)
fullI3 = Array{Float64}(I, 3, 3)
fullI3 = Array{Float64,2}(I, 3, 3)
fullI3 = zeros(3,3) + I

View file

@ -0,0 +1,11 @@
=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)

View file

@ -0,0 +1,17 @@
// version 1.0.6
fun main(args: Array<String>) {
print("Enter size of matrix : ")
val n = readLine()!!.toInt()
println()
val identity = Array(n) { IntArray(n) } // create n x n matrix of integers
// enter 1s in diagonal elements
for(i in 0 until n) identity[i][i] = 1
// print identity matrix if n <= 40
if (n <= 40)
for (i in 0 until n) println(identity[i].joinToString(" "))
else
println("Matrix is too big to display on 80 column console")
}

View file

@ -0,0 +1,8 @@
(defun identity
((`(,m ,n))
(identity m n))
((m)
(identity m m)))
(defun identity (m n)
(lists:duplicate m (lists:duplicate n 1)))

View file

@ -0,0 +1,6 @@
> (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))

View file

@ -0,0 +1,19 @@
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))+"]");
}
}
}

Some files were not shown because too many files have changed in this diff Show more