Implicit casting overhead from real to complex when multiplying two matrices

3 ビュー (過去 30 日間)
Is there an implicit casting overhead when multiplying a complex matrix by a real matrix to upcast the real matrix to complex or is it a natively-supported operation?
I have tried the following sample code but I get inconsistent results when changing the matrices dimension N.
N = 100;
A = rand(N);
B = rand(N);
C = complex(A);
tic
D1 = B*A;
toc
tic
D2 = B*C;
toc

採用された回答

Benjamin Thompson
Benjamin Thompson 2022 年 8 月 11 日
Multiplying a complex matrix by a real matrix requires fewer calculations so should take less time. Your test is a little too simple since B would have already been cached into memory for the second part. If you do B*A twice, it is a lot faster the second time.
  1 件のコメント
Daniele Giovannini
Daniele Giovannini 2022 年 8 月 23 日
You are right. I have tried to eliminate the cache from playing a role in two ways:
  • having variables small enough to fit in the cache (my CPU cache is 3 MB) at the same time and repeating many times each matrix product
  • having variables so big that they cannot possibly be cached and perform each matrix product only once
Both ways seem to confirm your answer. I am reporting my test code for completeness.
% Test 1
N = 150;
C = crand(N);
A_R = rand(N);
A_C = complex(A_R);
whos
tic
for n = 1:1e4
D1 = C*A_R;
end
toc
tic
for n = 1:1e4
D2 = C*A_C;
end
toc
% Test 2
N = 3000;
C = crand(N);
A_R = rand(N);
A_C = complex(A_R);
whos
tic
D1 = C*A_R;
toc
tic
D2 = C*A_C;
toc

サインインしてコメントする。

その他の回答 (1 件)

James Tursa
James Tursa 2023 年 7 月 10 日
This is not a natively supported operation (to use your terms). Yes, the real matrix must be first upconverted to a complex matrix (deep data copy with interleaved 0's) in order to call the BLAS matrix multiply routines in the background, since the BLAS library has no mixed complex-real routines. This will be a performance hit because of the deep data copy and all those unnecessary 0 multiplies. See the related discussion and explanations here:

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by