0

I have a vector whose elements identify the indices (per column) that I need to set in a different matrix. Specifically, I have:

A = 7
    1
    2

and I need to create a matrix B with some number of rows of zeros, except for the elements identified by A. In other words, I want B:

B = zeros(10, 3); % number of rows is known; num columns = size(A)
B(A(1), 1) = 1
B(A(2), 2) = 1
B(A(3), 3) = 1

I would like to do this without having to write a loop.

Any pointers would be appreciated.

Thanks.

AIjunkie
  • 3
  • 1

1 Answers1

0

Use linear indexing:

B = zeros(10, 3);
B(A(:).'+ (0:numel(A)-1)*size(B,1)) = 1;

The second line can be written equivalently with sub2ind (may be a little slower):

B(sub2ind(size(B), A(:).', 1:numel(A))) = 1;
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Thank you, that works. What does the trailing .' do in the expression A(:).' ? – AIjunkie Nov 01 '14 at 00:03
  • It's a transpose. `A(:).'` is just `A` but making sure it's a row vector – Luis Mendo Nov 01 '14 at 00:13
  • I see -- I've been using the single quote as the transpose operator; didn't really see anyone use it with a period, so that threw me off. – AIjunkie Nov 01 '14 at 00:15
  • That's one of my pet peeves :-) The single quote introduces a complex conjugate in addition to the tranpose. See a discussion [here](http://stackoverflow.com/q/25150027/2586922) – Luis Mendo Nov 01 '14 at 00:20