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

232 ビュー (過去 30 日間)
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.

採用された回答

Daniele Mascali
Daniele Mascali 2021 年 3 月 19 日
Try this:
real(A(imag(A) == 0))
  2 件のコメント
Rik
Rik 2021 年 3 月 19 日
If you run into any issues with float rounding errors:
A = [ -0.4406 - 1.5696i , -0.4406 + 1.5696i, 1.8812 + 0.0000i];
A(4)= 1 + 1i*(sqrt(2)^2-2); % imaginary part should be 0 but isn't quite
B1=real(A(imag(A) == 0));
B2=real(A(abs(imag(A))<(10*eps)));
disp(A),disp(B1),disp(B2)
-0.4406 - 1.5696i -0.4406 + 1.5696i 1.8812 + 0.0000i 1.0000 + 0.0000i 1.8812 1.8812 1.0000
Mathieu NOE
Mathieu NOE 2021 年 3 月 19 日
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

サインインしてコメントする。

その他の回答 (2 件)

Mathieu NOE
Mathieu NOE 2021 年 3 月 19 日
hello
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 件のコメント
Stephen23
Stephen23 2021 年 3 月 19 日
編集済み: Stephen23 2021 年 3 月 19 日
+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

サインインしてコメントする。


Ahmadreza Torabi
Ahmadreza Torabi 2021 年 12 月 15 日
編集済み: Ahmadreza Torabi 2021 年 12 月 15 日
Hello
You can use something like this:
A = [1 2 7+i 3 8+i 4 9+i 5 6];
m = 1;
n = length(A);
for k = 1:n
if isreal(A(k))
B(m) = A(k);
m = m+1;
end
end
B
B = 1×6
1 2 3 4 5 6
Then B is just include real numbers of A.
  1 件のコメント
Rik
Rik 2021 年 12 月 15 日
This will dynamically grow the array. It is better to create a logical vector of the same size as A where you mark wether it should be removed. Then you only need to modify the B once: when you create it.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by