Task

Build an   identity matrix   of a size known at run-time.



An identity matrix is a square matrix of size n × n,

where the diagonal elements are all 1s (ones),

and all the other elements are all 0s (zeroes).







I

n


=


[



1


0


0


⋯


0




0


1


0


⋯


0




0


0


1


⋯


0




⋮


⋮


⋮


⋱


⋮




0


0


0


⋯


1



]




{\displaystyle 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}}}





Related tasks

   Spiral matrix
   Zig-zag matrix 
   Ulam_spiral_(for_primes)


 
(* ****** ****** *)
//
// 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] *)
 