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?

+3


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:

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

      



And Mr. Azzaman's suggestion to avoid zeros

using intialising A

by doing A(n,n)=0;

.

+5


source


If bsxfun

allowed, then



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

      

+2


source


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;

      

+1


source







All Articles