How to Create an ID Matrix without Eyes and Loops

I'm just wondering if it is possible to create a single matrix without the eye function, loop and any matlab build function. At first I thought to use something like this:

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


Unfortunately I don't think I can assign the values ​​'1' and '0' without using some kind of loop. and this still uses the build function. any idea?


source to share

3 answers

Using a neat trick that A(1:n+1:end)

refers to elements A

that must be 1, you can simply do:



And Mr. Azzaman's suggestion to avoid zeros

using intialising A

by doing A(n,n)=0;




If bsxfun

allowed, then

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




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




All Articles