user103828
user103828

Reputation: 156

Create matrix: first n rows, 1st column has 1s and all other columns 0s, the next n rows, 2nd column has 1s and all other columns 0s and so forth

I would like to generate a matrix where in the first n rows, the first column has 1s and all other columns have 0s. In the next n rows, the second column has 1s and all other columns have 0s and so forth. For example, when n=2 and the number of columns is 3 then the matrix would look like this

A =

 1 0 0 
 1 0 0 
 0 1 0 
 0 1 0 
 0 0 1
 0 0 1

If m is the number of columns I used kron(eye(m),ones(n,1)). Are there other ways to do this?

Upvotes: 1

Views: 160

Answers (1)

Dan
Dan

Reputation: 45752

I don't know what "better" means but here are some alternatives to kron(eye(m),ones(n,1)):

reshape(repmat(permute(eye(m),[3,2,1]),n,1),[],m)

or

reshape(bsxfun(@times,ones(n,1),permute(eye(m),[3,2,1])),[],m)

or

reshape(meshgrid(eye(m),ones(n,1)),[],m)

or

I = eye(m);
I(ceil((1:m*n)./n),:)

or

N = n*m;
z = zeros(N,m);
z(sub2ind([N,m],1:N,ceil((1:N)./n))) = 1

or

C = mat2cell(ones(n,m),n,ones(1,m));
blkdiag(C{:})

You can compare the speed using the timeit function

Upvotes: 3

Related Questions