MATLAB Answers

Extracting only real numbers from a vector containing both real and complex values

14 views (last 30 days)
Tanveer Ashiq
Tanveer Ashiq on 19 Mar 2021
Edited: Stephen on 19 Mar 2021
Hi, I have a matrix that contains both real and complex elements in it. How can I transfer all the real elements (NOT the real parts of all elements) to another matrix?
For example:
My orginal matrix is A:
A = [ -0.4406 - 1.5696i , -0.4406 + 1.5696i, 1.8812 + 0.0000i]
Here we see that A has 3 elements, the first two of which are complex while the third element is real. How do I write code that extracts only the real element ie, the third element (1.8812)?
I do NOT want to extract the real parts of all three variables.

Accepted Answer

Daniele Mascali
Daniele Mascali on 19 Mar 2021
Try this:
real(A(imag(A) == 0))
Mathieu NOE
Mathieu NOE on 19 Mar 2021
that's why I suggested to make a test with a given tolerance and not exact zero match with risks of wrong answer due to rounding errors

Sign in to comment.

More Answers (1)

Mathieu NOE
Mathieu NOE on 19 Mar 2021
see code below :
A = [ -0.4406 - 1.5696i , -0.4406 + 1.5696i, 1.8812 + 0.0000i];
tol = eps;
ind = find(abs(imag(A))<tol);
B = A(ind);
  1 Comment
Stephen on 19 Mar 2021
+1 A slightly larger tolerance might also be more robust, e.g. 1e-10
find is not required, logical indexing is simpler and more efficient:
tol = 1e-10;
idx = abs(imag(A))<tol;
B = A(idx)
B = 1.8812

Sign in to comment.




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by