使用索引向量更改矩阵值

时间:2014-12-18 15:29:45

标签: performance matlab matrix vectorization

我有以下数组:

AA = zeros(5,3);
AA(1,3)=1;
AA(3,3)=1;
AA(4,2)=1;

我希望将值1放在由以下定义的collumns中 向量a = [0; 2; 0; 0; 1]。该向量的每个值都指的是柱子 我们想要在每行中更改的索引。如果为零,则不应进行任何更改。

期望的输出:

0     0     1
0     1     0
0     0     1
0     1     0
1     0     0

你能不提出循环来建议一种方法吗?目标是 更快的执行。

感谢!!!

1 个答案:

答案 0 :(得分:2)

方法1

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

方法2

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'第