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
.
Another, more vectorized way:
sel = a == real(a); % choose only real elements
only_reals = a( sel );
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]
Real numbers have an imaginary part of zero, so:
input_array(imag(input_array)==0);
ans =
1 3 -4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With