【问题标题】:Change the matrix values using index vector使用索引向量更改矩阵值
【发布时间】:2014-12-18 15:29:44
【问题描述】:

我有以下数组:

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 循环的方法?目标是 执行速度更快。

谢谢!!!

【问题讨论】:

    标签: performance matlab matrix vectorization


    【解决方案1】:

    方法 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) 格式的需要为我们获取有效的行和列索引。

    • sub2ind 为我们获取线性索引,我们可以使用它来索引输入矩阵 AA 并将 AA 中的那些设置为 1's。

    【讨论】:

    • 感谢直观的解释!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多