11

Matlab文档

为了速度和提高鲁棒性,您可以将复数 i 和 j 替换为 1i。例如,而不是使用

a = i;

采用

a = 1i;

稳健性部分很清楚,因为可能存在称为iorj的变量。但是,至于速度,我在 Matlab 2010b 中做了一个简单的测试,得到的结果似乎与声称相矛盾:

>>clear all

>> a=0; tic, for n=1:1e8, a=i; end, toc
Elapsed time is 3.056741 seconds.

>> a=0; tic, for n=1:1e8, a=1i; end, toc
Elapsed time is 3.205472 seconds.

有任何想法吗?会不会是版本相关的问题?

在@TryHard 和@horchler 发表评论后,我尝试为变量分配其他值a,结果如下:

经过时间的递增顺序:

“i” < “1i” < “1*i”(趋势“A”)

“2i” < “2*1i” < “2*i”(趋势“B”)

“1+1i” < “1+i” < “1+1*i”(趋势“A”)

“2+2i” < “2+2*1i” < “2+2*i”(趋势“B”)

4

2 回答 2

11

我认为你正在看一个病态的例子。尝试更复杂的东西(在 OSX 上显示 R2012b 的结果):

(重复添加)

>> clear all
>> a=0; tic, for n=1:1e8, a = a + i; end, toc
Elapsed time is 2.217482 seconds. % <-- slower
>> clear all
>> a=0; tic, for n=1:1e8, a = a + 1i; end, toc
Elapsed time is 1.962985 seconds. % <-- faster

(重复乘法)

>> clear all
>> a=0; tic, for n=1:1e8, a = a * i; end, toc
Elapsed time is 2.239134 seconds. % <-- slower
>> clear all
>> a=0; tic, for n=1:1e8, a = a * 1i; end, toc
Elapsed time is 1.998718 seconds. % <-- faster
于 2013-08-10T16:15:56.623 回答
6

要记住的一件事是,无论您是从命令行运行还是从保存的 M 函数运行,优化的应用方式都不同。

这是我自己的一个测试:

function testComplex()
    tic, test1(); toc
    tic, test2(); toc
    tic, test3(); toc
    tic, test4(); toc
    tic, test5(); toc
    tic, test6(); toc
end

function a = test1
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = 2 + 2i;
    end
end

function a = test2
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = 2 + 2j;
    end
end
function a = test3
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = 2 + 2*i;
    end
end

function a = test4
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = 2 + 2*j;
    end
end

function a = test5
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = complex(2,2);
    end
end

function a = test6
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = 2 + 2*sqrt(-1);
    end
end

在我运行 R2013a 的 Windows 机器上的结果:

>> testComplex
Elapsed time is 0.946414 seconds.    %// 2 + 2i
Elapsed time is 0.947957 seconds.    %// 2 + 2j
Elapsed time is 0.811044 seconds.    %// 2 + 2*i
Elapsed time is 0.685793 seconds.    %// 2 + 2*j
Elapsed time is 0.767683 seconds.    %// complex(2,2)
Elapsed time is 8.193529 seconds.    %// 2 + 2*sqrt(-1)

请注意,在调用顺序被打乱的不同运行中,结果会略有波动。因此,对时间持保留态度。

1i我的结论是:如果您使用or ,则速度无关紧要1*i


一个有趣的区别是,如果您在函数范围内也有一个变量并将其用作虚数单位,则 MATLAB 会引发错误:

Error: File: testComplex.m Line: 38 Column: 5
"i" previously appeared to be used as a function or command, conflicting with its
use here as the name of a variable.
A possible cause of this error is that you forgot to initialize the variable, or you
have initialized it implicitly using load or eval.

要查看错误,请将上述test3函数更改为:

function a = test3
    a = zeros(1e7,1);
    for n=1:1e7
        a(n) = 2 + 2*i;
    end
    i = rand();        %// added this line!
end

即,该变量i在同一局部范围内既用作函数又用作变量。

于 2013-08-10T20:40:18.517 回答