matlabmatrix

Identity matrix in MATLAB


I have to create a function in MATLAB that given a parameter N, it returns the N-by-N identity matrix. I cannot use loops, nor built-in functions like eye or diag. I have tried the following:

function I = identity(n)
    I = zeros(n, n);
    p = [1:n;1:n]';
    I(p) = 1;
end

But, when I call it with I = identity(3); I obtain the following result:

I =

 1     0     0
 1     0     0
 1     0     0

And I don't understand why, because I thought MATLAB could use a vector as a matrix index, and the way I did it, I have that:

p =

 1     1
 2     2
 3     3

So when I do I(p) = 1, the first step should be I(1, 1) = 1 then I(2, 2) = 1 and so on. What am I not seeing?


Solution

  • Using no functions, just matrix indexing -

    A(N,N) = 0;
    A((N+1)*(0:N-1)+1) = 1
    

    Thus, the function becomes -

    function A = identity( N )
    A(N,N) = 0;
    A((N+1)*(0:N-1)+1) = 1;
    end