Reputation: 339
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?
Upvotes: 3
Views: 2499
Reputation: 13945
The way in which MATLAB indexes is column-major, therefore it fills matrix I
with linear indices contained in p
, starting at (1,1) then going to (2,1) and so on. Therefore it "sees" the indices as [1 2 3] and then again [1 2 3].
What you could do is change p
into a 1xn vector containing the appropriate linear indices.
For instance:
p = 1:n+1:n^2
gives rise to those indices:
p =
1 5 9
and the following matrix I
:
I =
1 0 0
0 1 0
0 0 1
yay!
Upvotes: 3
Reputation: 104565
Going with thewaywewalk's answer, we can achieve the same thing with the bsxfun
approach but without using any built-in functions... except for ones
. Specifically, we can use indexing to replicate rows and columns of vectors, then use the equality operator when finished. Specifically, we would first generate a row vector and column vector from 1:n
, replicate them so that they're respectively n x n
matrices, then use equality. The values in this matrix should only be equal along the diagonal elements and hence the identity is produced.
As such:
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 double
precision as row == col
would produce a logical
matrix. I didn't cast using the double
function because you said you can't use any built-in functions... but I took the liberty of using ones
, because in your solution you're using zeros
, which is technically a built-in function.
Upvotes: 0
Reputation: 25242
Is bsxfun
allowed?
function I = identity(n)
I = bsxfun(@eq,1:n,(1:n).');
end
Upvotes: 3
Reputation: 221754
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
Upvotes: 4