说我有一个矩阵
A = zeros(5, 5);
Run Code Online (Sandbox Code Playgroud)
我希望批量修改一些元素,而不是使用for循环进行循环.例如,我希望将标记pts_to_modify为1的元素更改为where
pts_to_modify=[[2 3]; [3 2]];
Run Code Online (Sandbox Code Playgroud)
所以我希望A成为
0 0 0 0 0
0 0 1 0 0
0 1 0 0 0
0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做的时候
A(pts_to_modify(:, 1), pts_to_modify(:, 2)) = 1,
Run Code Online (Sandbox Code Playgroud)
我明白了
A =
0 0 0 0 0
0 1 1 0 0
0 1 1 0 0
0 0 0 0 0
0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能正确?
你可以使用sub2ind:
>> ind = sub2ind(size(A), pts_to_modify(1,:), pts_to_modify(2,:))
ind =
12 8
>> A(ind) = 1
A =
0 0 0 0 0
0 0 1 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)