基于行和列索引向量分配新的矩阵值
MatLab的新功能(R2015a,Mac OS 10.10.5),并希望找到解决此索引问题的方法。
New to MatLab here (R2015a, Mac OS 10.10.5), and hoping to find a solution to this indexing problem.
我想基于一个行索引向量和一个列索引来更改大型二维矩阵的值。举个简单的例子,如果我有一个3 x 2的零矩阵:
I want to change the values of a large 2D matrix, based on one vector of row indices and one of column indices. For a very simple example, if I have a 3 x 2 matrix of zeros:
A = zeros(3, 2)
0 0
0 0
0 0
我想改变A(1,1)= 1,A(2,2)= 1,A(3,1)= 1,这样A现在是
I want to change A(1, 1) = 1, and A(2, 2) = 1, and A(3, 1) = 1, such that A is now
1 0
0 1
1 0
我想用向量来表示行和列索引:
And I want to do this using vectors to indicate the row and column indices:
rows = [1 2 3];
cols = [1 2 1];
有没有办法在没有循环的情况下执行此操作?请记住,这是一个需要在非常大的2D矩阵上工作的玩具示例。为了额外的功劳,我是否还可以添加一个向量来指示要插入的值,而不是将其固定为1?
Is there a way to do this without looping? Remember, this is a toy example that needs to work on a very large 2D matrix. For extra credit, can I also include a vector that indicates which value to insert, instead of fixing it at 1?
我的循环方法很简单,但很慢:
My looping approach is easy, but slow:
for i = 1:length(rows)
A(rows(i), cols(i)) = 1;
end
sub2ind 可以在这里提供帮助,
sub2ind can help here,
A = zeros(3,2)
rows = [1 2 3];
cols = [1 2 1];
A(sub2ind(size(A),rows,cols))=1
A =
1 0
0 1
1 0
带有'insert'的向量
with a vector to 'insert'
b = [1,2,3];
A(sub2ind(size(A),rows,cols))=b
A =
1 0
0 2
3 0