3

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?

2
  • @johnny5 It's not, but it's very ill-formed and unclear. The answer by beaker below clarifies what OP wants, and it's even on-topic. Commented Jan 31, 2016 at 16:00
  • In general, be careful about expecting 1s and 0s to be treated as logical. Consider: >> foo = 1:10; >> foo([1,0,1,0,1,0,1,0,1,0]) Subscript indices must either be real positive integers or logicals. >> foo(logical([1,0,1,0,1,0,1,0,1,0])) ans = 1 3 5 7 9 Commented Feb 1, 2016 at 14:17

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Mentalist badge, +1 ;)
@AndrasDeak I've been working out with my Jedi Force Trainer.
For people using octave, broadcasting allows to write simply (1:10) == [2 5].'
@ederag Very true, and I actually generated the sample above on Octave. But I didn't want to confuse things as the question is only tagged MATLAB and not Octave.
4

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

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.