Identity matrix in Matlab

I need to create a function in Matlab that sets a parameter to N, returns an N-by-N identity matrix. I cannot use loops and built-in functions like eye

or diag

. I've 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 get 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 this:

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 can't I see?

+3


source to share


4 answers


Without any functions, just matrix indexing

-

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

      



So the function becomes -

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

      

+4


source


The way MATLAB indices are large in column size, so fills the matrix with I

linear indices contained in p

, starting at (1,1) then going down to (2,1), etc. Therefore, he "sees" the indices as [1 2 3], and then again [1 2 3].

What you can do is change p

to a 1xn vector containing the corresponding linear indices.

For example:

p = 1:n+1:n^2

      

spawns those indices:



p =

     1     5     9

      

and the following matrix I

:

I =

     1     0     0
     0     1     0
     0     0     1

      

yay!

+3


source


Is it possible ? bsxfun

function I = identity(n)

I = bsxfun(@eq,1:n,(1:n).');

end

      

+3


source


Going with the answer on the track, we can achieve the same approach with bsxfun

, but without using any built-in functions ... except ones

. Specifically, we can use indexing to replicate the rows and columns of vectors, and then use the equality operator upon completion. Specifically, we first generated a row vector and a column vector from 1:n

, copy them so that they match matrices n x n

, and then use equality. The values ​​in this matrix must be equal only along the diagonal elements and therefore an identity is produced.

Thus:

row = 1:n;
col = row.';
row = row(ones(n,1),:);
col = col(:, ones(n,1));
I = (row == col) + 0;

      

We need to add 0

to the output matrix to convert the matrix to precision double

as it row == col

will create a matrix logical

. I didn't use the function double

because you said you can't use any built-in functions ... but I allowed the use ones

because in your solution you are using zeros

, which is technically a built-in function.

0


source







All Articles