Extract real number from array in matlab

I would like to extract only real numbers from an array containing imaginary numbers, and I would like to remove imaginary numbers from an array. Therefore, from an array of 10 elements, of which 5 are real and 5 imaginary, you need to get an array of 5 elements, which should be an element of real numbers. This is in MATLAB

EDIT:

Adding an Example

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

The desired result will be

 output = [ 1, 3, -4 ]; 

which contains only valid input_array elements.

+7
source share
4 answers

Another, more vectorial way:

 sel = a == real(a); % choose only real elements only_reals = a( sel ); 
+11
source

You can use isreal in combination with arrayfun to check if the numbers are real and / or real , just to 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] 
+5
source

Real numbers have an imaginary part of zero, therefore:

 input_array(imag(input_array)==0); ans = 1 3 -4 
+4
source

You can do this with isreal . Turning off isreal does not give vector output, which is strange for MATLAB, as 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 believe that great people will come to a decision without a loop.

Shay edit:

Version with preliminary distribution of the output

 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 cycles (see other answers). But for this loop version, preselection is an important component.

+3
source

All Articles