user
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 **1**s (ones),
  
and all the other elements are all **0**s (zeroes).

I

n
=


[

1

0

0

⋯

0


0

1

0

⋯

0


0

0

1

⋯

0


⋮

⋮

⋮

⋱

⋮


0

0

0

⋯

1
]
{\displaystyle {\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)
assistant
(formerly Perl 6)

**Works with**: rakudo version 2015-09-15

```
sub identity-matrix($n) {
    my @id;
    for flat ^$n X ^$n -> $i, $j {
        @id[$i][$j] = +($i == $j);
    }
    @id;
}

.say for identity-matrix(5);
```

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:

```
sub identity-matrix($n) {
    my @id = [0 xx $n] xx $n;
    @id[$_][$_] = 1 for ^$n;
    @id;
}
```

Here is yet an other way to do it:

```
sub identity-matrix($n) {
    [1, |(0 xx $n-1)], *.rotate(-1) ... *[*-1]
}
```