Let’s do it in two simple lines and without zeros
… The first line creates a n x n
matrix where all elements are 0
. After you can (as your hint says) address the elements with a single argument. The distance between the ones in the identity matrix are n+1
. This way you write the ones with the mentioned distance until the end.
function out = identity(n)
out(n,n) = 0;
out(1:n+1:end) = 1;
end