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)


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
}