问题
Is there a way to update different column in each row of matrix, where row indices are stored in vector.
Example
mx = zeros(10,10);
cols = [2 3 5 4 6 8 9 1 2 3]';
for i = 1:size(mx,1)
mx(i,cols(i)) = 1;
end
mx
produces
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
The question is, whether I can do it without the for loop?
回答1:
You can address elements in a matrix with a single number. In this case the elements are numbered columnwise (1-10 is the first column, 11-20 the secound...) and there is a function sub2ind
to calculate the element number for you. In your case its pretty easy, because its a 10x10 so you could do it manually, but i would still recommend the function.
mx = zeros(10,10);
rows = 1:size(mx,1); %create the row indices
cols = [2 3 5 4 6 8 9 1 2 3];
X=sub2ind(size(mx),rows,cols)
mx(X)=1;
mx
来源:https://stackoverflow.com/questions/48022920/update-matrix-single-column-per-row-where-row-index-is-in-vecor