MATLAB: Change the value of a matrix element based on the index given in another matrix

indexingMATLABmatrix manipulationvectorization

I have 2 matrices. One all zeroes, one is a vector of numbers. In the first matrix, I want to switch 1 element/row (to the value 1) based on the value in the second matrix (represents the index). For example:
m1=zeros(3);
m2=[ 1 3 2 ];
result= [1 0 0; 0 0 1; 0 1 0];
Is there a way to vectorize this and thus do this without a for-loop?
result=zeros(3);
m2=[ 1 3 2 ];
for i = 1:3
result(i,m2(i)) = 1;
end
Thanks a lot for your help.

Best Answer

Method one: sub2ind:
>> a = zeros(3);
>> c = [1,3,2];
>> r = 1:size(a,1);
>> a(sub2ind(size(a),r,c)) = 1
a =
1 0 0
0 0 1
0 1 0
Method two: constructed linear indices:
>> a = zeros(3);
>> a(c + (0:3:8)) = 1;
>> a = a.'
a =
1 0 0
0 0 1
0 1 0