How can I use values vectors to do element-by-element indexing in a matrix?

If I have two vectors, how do I use the values in each of those vectors for element-by-element indexing without using a loop.
With loop it will look like this:
A=[1,3,2]; B=[2,3,1];
for i=1:3 Z(A(i),B(i))=1; end
Solution is >> Z= [0 1 0; 1 0 0; 0 0 1]
I want to this without using the loop.
Following things didnot work:
Z(A,B)=1; Z(A(:),B(:))=1;
Thanks for looking into this.

 Accepted Answer

A=[1,3,2];
B=[2,3,1];
n=max(A)
m=max(B)
idx=sub2ind([n m],A,B)
Z=zeros(n,m)
Z(idx)=1

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!