最佳实践绝对是避免 Matlab 中的循环或递归。
之间sum(A(:))
和sum(sum(A))
。根据我的经验,Matlab 中的数组似乎作为堆叠列向量存储在内存中的连续块中。所以 A 的形状在 中并不重要sum()
。(可以在 Matlab 中测试reshape()
和检查整形是否很快。如果是,那么我们有理由相信数组的形状与数据存储和操作的方式没有直接关系。)
因此,没有理由sum(sum(A))
应该更快。如果 Matlab 实际创建一个行向量,首先记录 A 的每一列的总和,然后对各列求和,它会更慢。但我认为sum(sum(A))
在用户中非常普遍。他们很可能将它们硬编码sum(sum(A))
为单个循环,与sum(A(:))
.
下面我提供一些测试结果。在每个测试中,A=rand(size) 和 size 在显示的文本中指定。
首先是使用tic toc。
Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.
Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.
Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.
Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27 (line 70)
A=rand(100000000,1);
下面是使用 cputime
Size 100x100
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x1
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000x1000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 1000000
The cputime for sum(A(:)) in seconds is
0
The cputime for sum(sum(A)) in seconds is
0
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.
Error in test27_2 (line 70)
A=rand(100000000,1);
以我的经验,这两个计时器都只在 0.1 秒内有意义。因此,如果您对 Matlab 计时器有类似的经验,则没有一个测试可以辨别sum(A(:))
和sum(sum(A))
.
我又尝试了几次我电脑上允许的最大尺寸。
Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.
Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.2808
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
Size 10000x10000
The cputime for sum(A(:)) in seconds is
0.312
The cputime for sum(sum(A)) in seconds is
0.312
它们看起来是等价的。任何一个都很好。但sum(sum(A))
要求您知道数组的维度是 2。