Stud12 Stud
Stud12 Stud

Reputation: 31

Convert integer to logical array in MATLAB

I want to convert an integer i to a logical vector with an i-th non-zero element. That can de done with 1:10 == 2, which returns

0     1     0     0     0     0     0     0     0     0

Now, I want to vectorize this process for each row. Writing repmat(1:10, 2, 1) == [2 5]' I expect to get

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

But instead, this error occurs:

Error using ==
Matrix dimensions must agree.

Can I vectorize this process, or is a for loop the only option?

Upvotes: 3

Views: 820

Answers (3)

Daniel
Daniel

Reputation: 36710

Just another possibility using indexing:

n = 10;
ind = [2 5];
x=zeros(numel(ind),n);
x(sub2ind([numel(ind),n],1:numel(ind),ind))=1;

Upvotes: 2

rayryeng
rayryeng

Reputation: 104484

Another way is to use eye and create a logical matrix that is n x n long, then use the indices to index into the rows of this matrix:

n = 10;
ind = [2 5];

E = eye(n,n) == 1;
out = E(ind, :);

We get:

>> out

out =

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

Upvotes: 4

beaker
beaker

Reputation: 16791

You can use bsxfun:

>> bsxfun(@eq, 1:10, [2 5].')
ans =

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

Note the transpose .' on the second vector; it's important.

Upvotes: 9

Related Questions