我有以下数组:
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)
格式需要分别获取VALID行索引和列索引。
sub2ind
向我们获取线性索引,我们可以使用它来索引输入矩阵AA
并将其设置AA
为1
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句