Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 使用索引向量更改矩阵值_Performance_Matlab_Matrix_Vectorization - Fatal编程技术网

Performance 使用索引向量更改矩阵值

Performance 使用索引向量更改矩阵值,performance,matlab,matrix,vectorization,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]。该向量的每个值都是指COLLMN 我们希望在每行中更改的索引。零apears时,不应进行任何更改 期望输出: 0 0 1 0 1 0 0 0 1 0 1 0 1 0 0 你能建议一种不用for循环的方法吗?目标是 更快的执行

我有以下数组:

AA = zeros(5,3);
AA(1,3)=1;
AA(3,3)=1;
AA(4,2)=1;
我想把值1放在下面定义的collumns中 向量
a=[0;2;0;0;1]
。该向量的每个值都是指COLLMN 我们希望在每行中更改的索引。零apears时,不应进行任何更改

期望输出:

0     0     1
0     1     0
0     0     1
0     1     0
1     0     0
你能建议一种不用for循环的方法吗?目标是 更快的执行

谢谢

方法1 带有给定AA的代码输出-

>> AA
AA =
     0     0     1
     0     1     0
     0     0     1
     0     1     0
     1     0     0

方法2 将其分解为几个步骤进行解释:

  • find(a~=0)
    a(a~=0)
    根据需要分别为
    sub2ind(size(),row,column)
    格式获取有效的行和列索引

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


感谢您的直观解释!!
>> 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