2
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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
user42459
  • 883
  • 3
  • 12
  • 29
  • Although different programming languages call them different things, a vector/array is a fundamentally different data structure than a list/cell array. See http://stackoverflow.com/questions/393556/when-to-use-a-linked-list-over-an-array-array-list but in short: Vectors/arrays offers O(1) reads and writes, but O(N) appends (writes beyond the array)—basically a bigger array has to be allocated by the operating system and all N elements of the original array copied to the new space. Lists offer O(N) reads and writes, but O(1) pre-pends and appends (if doubly-linked). – Ahmed Fasih Jul 22 '16 at 01:17
  • Matlab’s arrays are proper arrays: constant index time. The only way to achieve this is to guarantee that each element takes up exactly the same amount of memory, i.e., each element has fixed type (float32, float64, complex64, complex128, etc.). When you insert/append a complex value into a float64 array in Matlab, in order for the array to keep its O(1) lookup, Matlab has to create a new array of type complex128, copy the old array into the new one, and add your new complex value. – Ahmed Fasih Jul 22 '16 at 01:20

1 Answers1

8

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
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 3
    Just to emphasise that the `complex` attribute is a property of the array, not the entries in the array: note that `isreal` returns a single output for a whole array. `isreal(3)` is true, and `isreal(complex(3,0))` is false, even though `complex(3,0)` has a zero imaginary part. – Sam Roberts Jul 20 '16 at 13:52