Matlab中的单位矩阵

时间:2015-04-22 22:35:29

标签: matlab matrix

我必须在Matlab中创建一个给定参数N的函数,它返回N-by-N单位矩阵。我不能使用循环,也不能使用eyediag等内置函数。我尝试过以下方法:

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

但是,当我用I = identity(3);调用它时,我得到以下结果:

I =

 1     0     0
 1     0     0
 1     0     0

我不明白为什么,因为我认为Matlab可以使用向量作为矩阵索引,而我这样做的方式,我有:

p =

 1     1
 2     2
 3     3

所以当我I( p ) = 1时,第一步应该是I( 1,1 ) = 1然后是I( 2,2 ) = 1,依此类推。我没看到什么?

4 个答案:

答案 0 :(得分:4)

不使用任何功能,只需matrix indexing -

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

因此,该功能变为 -

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

答案 1 :(得分:3)

MATLAB索引的方式是列主要,因此它填充矩阵I,其中包含p中包含的线性索引,从(1,1)开始,然后转到(2,1)并且等等。因此,它“看到”指数为[1 2 3],然后再“[1 2 3]。

您可以做的是将p更改为包含相应线性索引的1xn向量。

例如:

p = 1:n+1:n^2

产生了这些指数:

p =

     1     5     9

以及以下矩阵I

I =

     1     0     0
     0     1     0
     0     0     1

耶!

答案 2 :(得分:3)

是否允许bsxfun

function I = identity(n)

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

end

答案 3 :(得分:0)

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.