extract real number from array in matlab

carminePat picture carminePat · Dec 13, 2012 · Viewed 10.6k times · Source

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.

Answer

Shai picture Shai · Dec 13, 2012

Another, more vectorized way:

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

only_reals = a( sel );