给定3个向量,我将如何通过向量化形成以下数组?

时间:2018-02-18 11:35:46

标签: matlab

我有以下3个向量:

C =

 8
 9
10
14
15
16
20
21
22


R =

14
15
16
20
21
22
25
26
27


L =

 3
 4
 5
 8
 9
10
14
15
16

这些数组中的数字从1到d运行,其中d是整数。

我想形成一个d x d数组,以满足以下模式:

Row 8 of O should have non-zero columns 8,14,3 such that
O(8,8) = 1
O(8,14) = 2
O(8,3) = -1

Row 9 of O should have non-zero columns 9,15,4.
O(9,9) = 1
O(9,15) = 2
O(9,4) = -1

...

其他地方都有零。

基本上,我想优化

for i = 1:length(C)
    A(C(i),[R(i) C(i) L(i)]) = [1 2 -1]; 
 end

1 个答案:

答案 0 :(得分:1)

怎么样:

  clc; clear;
  C=[8 9 10 14 15 16 20 21 22]';
  R=[14 15 16 20 21 22 25 26 27]';
  L=[3 4 5 8 9 10 14 15 16]';

  %test A
  tic
  for ii=1:100000
    A=zeros(27);
    for i = 1:length(C)
      A(C(i),[R(i) C(i) L(i)]) = [1 2 -1]; 
    end;
  end
  toc

  %optimize
  tic
  for ii=1:100000
    B=zeros(27);
    v=ones(length(C),1);
    B([C C C]+([R C L]-1)*27)=[v v*2 -v];
  end
  toc

  %check
  isequal(A,B)

输出结果为:

Elapsed time is 0.854814 seconds.
Elapsed time is 0.708940 seconds.

ans =

     1

感谢Tommaso Belluzzo提供的有用评论!