Tim
Tim

Reputation: 99418

how to eliminate complex number in a vector in Matlab

In Matlab, suppose there is a vector whose elements can be complex or real. I was wondering how to remove the nonreal elements, and consequently reduce the size of the vector? Thanks and regards!

Upvotes: 5

Views: 36472

Answers (3)

Pablo
Pablo

Reputation: 8644

You can also avoid testing in a loop using Matlab's vector syntax:

x = [1, 2, 3+1i, 4+2i, 5+3i, 6, 7, 8+4i, 9+0.000001i]
y = x(imag(x) == 0);
z = real(x(abs(imag(x)) < 0.00001));

y should be [1,2,6,7] and z should be [1,2,6,7,9]

imag(x) == 0 yields a logical vector with true values whenever the equality condition holds. x(<logical vector>) yields a new vector with only the elements of x where <logical vector> was true.

Upvotes: 5

Rosh Oxymoron
Rosh Oxymoron

Reputation: 21055

That's a very unusual thing to ask. Since the imaginary part is a floating point number, you can't really tell which number is a real number and which number is very close to a real number. Such function doesn't exist in Matlab since it's not very clear how it would be useful for anything (it doesn't make much sense to remove those numbers). Specifying your actual purpose here might help you get better answers.

If you want to ensure that only real numbers are left in the vector, you can use the following (it doesn't work with matrices and vertical rows, but you've got the idea):

x = [1, 2, 3+1i, 4+2i, 5+3i, 6, 7, 8+4i, 9+0i]
z = []
for k = [1:length(x)]
    if imag(x(k)) == 0
        z = [z, real(x(k))]
    endif
endfor

If you want to keep all numbers that are close to a real number, but could have some small non-zero imaginary part, you can use the following:

x = [1, 2, 3+1i, 4+2i, 5+3i, 6, 7, 8+4i, 9+0.000001i]
z = []
for k = [1:length(x)]
    if abs(imag(x(k))) < 0.00001
        z = [z, real(x(k))]
    endif
endfor

Of course, if you tell us what your actual criterion is, it would be much easier to give you a better idea. Are you looking for the real solutions to some sort of equation or system of equations, real roots of a polynomial? In this case, the first one might miss a real solution because of the approximation error, and the second one can give you things that aren't solutions.

Upvotes: 2

b3.
b3.

Reputation: 7165

Use the REAL and IMAG functions:

>> x = [1+i; 4+3i; 5+6i]

x =

                          1 +                     1i
                          4 +                     3i
                          5 +                     6i

>> real(x)

ans =

     1
     4
     5

>> imag(x)

ans =

     1
     3
     6

EDIT

The above doesn't answer the poster's question. This does.

Use the FIND and REAL functions:

>> v = [1+i; 2; 3]

v =

                          1 +                     1i
                          2                         
                          3                         

>> v(v == real(v))

ans =

     2
     3

Upvotes: 13

Related Questions