Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract real number from array in matlab [duplicate]

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.

like image 390
carminePat Avatar asked Dec 13 '12 12:12

carminePat


3 Answers

Another, more vectorized way:

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

only_reals = a( sel );
like image 153
Shai Avatar answered Sep 27 '22 01:09

Shai


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]
like image 34
Gunther Struyf Avatar answered Sep 23 '22 01:09

Gunther Struyf


Real numbers have an imaginary part of zero, so:

input_array(imag(input_array)==0);

ans =
    1     3    -4
like image 27
nrz Avatar answered Sep 25 '22 01:09

nrz