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)


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