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)


 
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
 