最佳做法无疑是避免马特拉布的漏洞或休妻。
Between sum(A(:))
and sum(sum(A))
.
In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum()
. (One can test reshape()
and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)
因此,没有理由加快<代码>(摘要(A)代码>。 如果Matlab实际上制造了一种滚动矢量,记录A一栏中每一栏的总和,然后比各栏中的总和,则会放缓。 但我想sum((sum(A))
在用户中广为传播。 硬编码<代码>sum(((A))可能是一种单一形式,与<代码>sum(A(:)相同。
下面我提供一些检测结果。 在每次测试中,A=rand(size)和大小在显示的文本中都有具体规定。
首先是使用斜线。
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);
下面是使用假肢
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);
在我的经验中,两个时间都只是有意义的。 因此,如果你在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
They seem equivalent.
Either one is good. But sum(sum(A))
requires that you know the dimension of your array is 2.