7

I would like to extract only the real numbers from an array containing imaginary numbers also I would like to eliminate the imaginary numbers from array. Therefore, from an array of 10 elements, of which 5 real, and 5 imaginary, to obtain an array of only 5 elements, which must be the real numbers element. This in MATLAB

EDIT:

Adding an example

input_array = [ 1, 1+i, -2+2*j, 3, -4, j ];

The desired output would be

output = [ 1, 3, -4 ];

which contains only real elements of input_array.

Shai
  • 111,146
  • 38
  • 238
  • 371
carminePat
  • 159
  • 2
  • 5
  • 13

4 Answers4

12

Another, more vectorized way:

sel = a == real(a); % choose only real elements

only_reals = a( sel );
Shai
  • 111,146
  • 38
  • 238
  • 371
5

You can use isreal in combination with arrayfun to check if numbers are real and/or real to just keep the real parts. Examples:

a = [1+i 2 3 -1-i];
realidx = arrayfun(@isreal,a);
only_reals = a(realidx);
only_real_part = real(a);

>> only_reals

  = [ 2  3]

>> only_real_part

  = [1 2 3 -1]
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58
4

Real numbers have an imaginary part of zero, so:

input_array(imag(input_array)==0);

ans =
    1     3    -4
nrz
  • 10,435
  • 4
  • 39
  • 71
3

You can do that with isreal function. Turns out isreal does not give a vector output, which is weird for MATLAB, since it usually does. So, you need to use a for loop.

arr = [1+i 5 6-3i 8];
arrReal = [];
for idx = 1:numel(arr)
    if isreal(arr(idx))
        arrReal(end+1) = arr(idx);
    end
end

I suppose great folks here will come up with a loopless solution.

Shai's edit:

A version with pre-allocation of output result

arrReal = NaN( size(arr) ); % pre-allocation
for idx = 1:numel(arr)
    if isreal( arr(idx) )
        arrReal(idx) = arr(idx);
    end
end
arrReal( isnan( arrReal ) ) = []; % discard non-relevant entries

Of course, this goal can be achieved without loops (see other answers). But for this loopy version, a pre-allocation is a significant ingredient.

HebeleHododo
  • 3,620
  • 1
  • 29
  • 38
  • an interesting use of `isreal`. However your answer has two major drawbacks: 1. it uses a loop (as you have already noted). 2. the output `arrReal` grows inside the loop. This type of memory usage causes Matlab to **really** slow down. A better way is to pre-allocate `arrReal` to the size of `arr` and remove the redundant part after the loop. Anyhow, thanks for your answer! – Shai Dec 13 '12 at 19:11
  • @Shai I thought about preallocation but could not come up with a way to index `arrReal` other than keeping another index variable. So, I decided not to. But I probably should have anyway. Do you know a more clever way? – HebeleHododo Dec 14 '12 at 06:03
  • I just edited your answer and added a version with pre-allocation. Hope you like it. – Shai Dec 15 '12 at 17:55
  • 1
    @Shai your edit had been rejected when I saw it. So, I copied your solution. – HebeleHododo Dec 17 '12 at 06:10