I want to replace value of n-th column of a matrix, based on a vector values, in a vectorized way.
Input:
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
Vector:
[2]
[4]
[1]
[3]
Expected output:
[0 1 0 0]
[0 0 0 1]
[1 0 0 0]
[0 0 1 0]
Matlab code with for-loop:
A = zeros(4,4);
b = [2; 4; 1; 3];
for row=1:4
A(row, b(row)) = 1;
endfor
Matlab code with sub2ind:
A = zeros(4,4);
b = [2; 4; 1; 3];
c = [[1:length(b)]' b];
A(sub2ind(size(A), c(:,1), c(:,2))) = 1;
Is there more vectorized way in Matlab? Thank you.