3
votes

I just wonder whether it's possible to create an identity matrix without eye function, loop, and any matlab build in function. At first I was thinking to use something like this:

A = bsxfun(@power, 1:n, (1:n).');

Unfortunately, I do not think I can assign value '1' and '0' without using any loop. and this still use build function. any idea?

3
Doesn't bsxfun count as a Matlab builtin function? - David
I don't understand the point of this other than it being a learning exercise. If bsxfun is acceptable, how about diag(ones(1,n))? - horchler

3 Answers

5
votes

Using the neat trick that A(1:n+1:end) references the elements of A that should be 1, you can simply do:

A=zeros(n^2,1);
A(1:n+1:end)=1;

And MrAzzaman's suggestion to avoid using zeros by intialising A by doing A(n,n)=0;.

2
votes

If bsxfun is allowed then

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

where num is the size of the nxn matrix.

function matrix = identity_matrix(num)
matrix = zeros(num);   //this creates a new n by n zero matrix
matrix(1:num+1:end)=1;