How do I initialize a complex array to zeros in MATLAB?

162 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2012 年 5 月 18 日
編集済み: Royi Avital 2020 年 12 月 29 日
MATLAB documentation recommends that pre-allocation of variables speeds up performance. I would like to pre-allocate a complex array in my code to zeros. However, when I type the following commands:
x = zeros(100,1) + j*zeros(100,1);
MATLAB creates a 100-by-1 real double array. I would like to create a complex array and initialize both the real and imaginary parts to zeros.

採用された回答

MathWorks Support Team
MathWorks Support Team 2012 年 5 月 18 日
A complex number can be created in MATLAB using the COMPLEX function. To initialize a complex number with zero as the real part and non-zero imaginary part, enter the following at the MATLAB command prompt
a = zeros(1,100);
x = complex(a,0);
To verify that the above command actually creates a 100-by-1 complex array, enter the following at the MATLAB command prompt
whos x
If you were to create the complex arrary with the above code and then assign a pure real number to one part of x or perform an arithmetic operation with a real number, MATLAB will de-allocate the complex part of the variable x . Type the following commands to observe this behavior:
x = x + 1.0;
whos x
When a real number, 1.0 was added to x, MATLAB de-allocates the complex part of the variable x and creates a 100-by-1 real double array. To keep the complex part, wrap COMPLEX around the expression.
  2 件のコメント
James Tursa
James Tursa 2016 年 11 月 10 日
編集済み: James Tursa 2016 年 11 月 10 日
You did an operation that resulted in the imaginary part of z being identically 0. MATLAB detected this result and deallocated the imaginary part. So you would have to follow this up with:
z = complex(z)
I think TMW comments were meant to be interpreted as a whole array assignment. E.g.,
x = complex(x + 1.0);
Qu Cao
Qu Cao 2017 年 1 月 9 日
Thank you for clarifying the answer.

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

その他の回答 (1 件)

Royi Avital
Royi Avital 2020 年 12 月 29 日
編集済み: Royi Avital 2020 年 12 月 29 日
In later versions one could do something like vB = zeros(3, 1, 'like', 1j);.

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by