user42459
user42459

Reputation: 915

Why does Matlab create imaginary parts when only one element becomes complex?

K>> asdfasdf=[1 1 1]

asdfasdf =
 1     1     1

K>> asdfasdf(4)=-2.3604 + 0.1536i

asdfasdf =
1.0000 + 0.0000i   1.0000 + 0.0000i   1.0000 + 0.0000i  -2.3604 + 0.1536i

Why did the first 3 elements suddenly become complex? And how can I prevent Matlab from doing this? Real is real. And this shouldn't change to imaginary just because another element is imaginary.

Upvotes: 2

Views: 299

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

The complex attribute is a property of the array, not of each entry. If an entry needs to be complex, then all entries are complex; or rather the array is.

You say

Real is real

but real is complex too. A complex number with zero imaginary part is the same (has the same value) as a real number.

Example with numbers:

>> x = 3; % real number

>> y = complex(3, 0); % force to be complex

>> whos x y % check that x is real and y is complex
  Name      Size            Bytes  Class     Attributes

  x         1x1                 8  double              
  y         1x1                16  double    complex   

>> x==y % are they equal?
ans =
     1

Example with arrays:

>> x = [2 3 4]; % real values: x is real

>> y = [x, 5+6j]; % include a complex value: y becomes complex

>> x(1:3)==y(1:3) % equal values?
ans =
     1     1     1

Upvotes: 8

Related Questions