Set a value of a specific column for each row of a matrix

折月煮酒 提交于 2020-07-16 05:49:13

问题


I have a matrix A with m rows and I'd like to set a specific element of each row equal 1. The column index varies from row to row and is specified by a column vector a (with m values). That is, I want A_{i,a_i} = 1. Is there a quick way to do this in Matlab (without a for-loop)?


回答1:


I solved it using the sub2ind function:

A(sub2ind(size(A), 1:numel(a), a')) = 1


来源:https://stackoverflow.com/questions/20957317/set-a-value-of-a-specific-column-for-each-row-of-a-matrix

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