Update matrix, single column per row where row index is in vecor

拟墨画扇 提交于 2021-02-10 19:40:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!