在两个矩阵之间复制值的最快方法

时间:2015-02-26 06:13:37

标签: matlab matrix

我正在寻找一种将矩阵的特殊值复制到其他矩阵的最快方法。假设我有矩阵A,例如

A =[4     1     5     4     4
   -2    -1     1     2     2
    3    -1     1     7     3
    5     3    -1     1    -2
    6     4     4    -1     1]

我的目标是复制元素,其值为1,-1为矩阵B.预期矩阵B,如

B =[ 0     1     0     0     0
     0    -1     1     0     0
     0    -1     1     0     0
     0     0    -1     1     0
     0     0     0    -1     1]

我执行了两种方法来创建矩阵B.但是,如果矩阵A的大小变大,我认为我的方式仍然不是最快的方式。我知道这个论坛有很多专家matlab的家伙。你能用另一种方式向我推荐吗? 这是我的代码

%%First way:
tic;B=((A==1)|(A==-1)).*A;toc
Elapsed time is 0.000026 seconds.
%%Second way:
tic;idx1=find(A==1);idx2=find(A==-1);B=zeros(size(A));B(idx1)=1; B(idx2)=-1;toc;B
Elapsed time is 0.000034 seconds.

2 个答案:

答案 0 :(得分:2)

我想到的唯一可能更快的事情是:

B = (abs(A) == 1).*A;

答案 1 :(得分:2)

这里有与@thewaywewalk相同的东西

B=A.*reshape(abs(A(:))==1,size(A));

这是我测试这些的方法:

A=randi(10,1000,1000)-7;
B1=@() ((A==1)|(A==-1)).*A;
B2=@() (abs(A) == 1).*A;
B3=@() A.*reshape(abs(A(:))==1,size(A));


timeit(B1)
ans =
0.0136

timeit(B2)
ans =
0.0080

timeit(B3)
ans =
0.0079

这些会在不同的运行中发生变化,但是这些方法是相同的...... 这是对一系列矩阵大小的相同测试:

enter image description here

相关问题