MATLAB: How to assign values to a column in each row where the column number for each row is specified in a vector

indexindexingMATLAB

Hello! I have a matrix of zeros of size [m,n]. I want to set one column in each row (colums will be different for each row). The column numbers are specified in a vector of size [m,1]. How do I implement this without a for loop?
eg. if I had a matrix zeros(2,2) and the vector was [1;2], I would expect a 2×2 identity matrix.
Thanks,
Tanay

Best Answer

Use sub2ind like this:
>> A = zeros(2,2);
>> idc = [2,1];
>> idx = sub2ind(size(A),1:numel(idc),idc);
>> A(idx) = 1
A =
0 1
1 0