我有以下数组:
AA = zeros(5,3);
AA(1,3)=1;
AA(3,3)=1;
AA(4,2)=1;
我想将值 1 放置在由以下向量定义的列中
a = [0; 2; 0; 0; 1]
该向量的每个值都指的是我们要在每行中更改的列索引。当出现零时,不应进行任何更改。
所需输出:
0 0 1
0 1 0
0 0 1
0 1 0
1 0 0
您能否建议一种无需 for 循环即可执行此操作的方法?目标是更快的执行。
谢谢!
nrows = size(AA,1) %// Get the no. of rows, as we would use this parameter later on
%// Calculate the linear indices with `a` as the column indices and
%// [1:nrows] as the row indices
idx = (a-1)*nrows+[1:nrows]' %//'
%// Select the valid linear indices (ones that have the corresponding a as non-zeros
%// and use them to index into AA and set those as 1's
AA(idx(a~=0))=1
给定的代码输出
AA
-
>> AA
AA =
0 0 1
0 1 0
0 0 1
0 1 0
1 0 0
AA(sub2ind(size(AA),find(a~=0),a(a~=0)))=1
将其分解为几个步骤进行解释:
find(a~=0)
和 a(a~=0)
分别为我们提供 sub2ind(size(),row,column)
格式所需的有效行索引和列索引。 sub2ind
为我们提供线性索引,我们可以用它来索引输入矩阵 AA
并将 AA
中的那些设置为 1
的。