ベスト プラクティスは、Matlab でループや再帰を避けることです。
sum(A(:))
との間sum(sum(A))
。私の経験では、Matlab の配列は、スタックされた列ベクトルとしてメモリ内の連続ブロックに格納されているようです。したがって、 A の形状は ではあまり重要ではありませんsum()
。reshape()
( Matlab で再形成が高速かどうかをテストして確認できます。高速である場合、配列の形状がデータの保存方法と操作方法に直接関係していないと考える理由があります。)
そのため、sum(sum(A))
高速にする必要はありません。Matlab が実際に A の各列の合計を記録する行ベクトルを最初に作成し、次に列の合計を作成すると、処理が遅くなります。しかし、私sum(sum(A))
はユーザーの間で非常に広まっていると思います。sum(sum(A))
と同じように、単一のループになるようにハードコーディングされている可能性がありsum(A(:))
ます。
以下に、いくつかのテスト結果を示します。各テストでは、A=rand(サイズ) とサイズが表示されたテキストで指定されます。
まずは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 であることを知っている必要があります。