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)


%rotates one list clockwise by one integer
rotate(Int,List,Rotated) :-
	integer(Int),
	length(Suff,Int),
	append(Pre,Suff,List),
	append(Suff,Pre,Rotated).
%rotates a list of lists by a list of integers
rotate(LoInts,LoLists,Rotated) :-
	is_list(LoInts),
	maplist(rotate,LoInts,LoLists,Rotated).
 
%helper function
append_(Suff,Pre,List) :-
	append([Pre],Suff,List).	
idmatrix(N,IdMatrix):-
	%make an N length list of 1s and append with N-1 0s
	length(Ones,N),
	maplist(=(1),Ones),
	succ(N0,N),
	length(Zeros,N0),
	maplist(=(0),Zeros),
	maplist(append_(Zeros),Ones,M),
	%create the offsets at rotate each row
	numlist(0,N0,Offsets),
	rotate(Offsets,M,IdMatrix).
 
main :-
	idmatrix(5,I),
	maplist(writeln,I).
 