# Logical with complex numbers in a vector

7 views (last 30 days)
Hmm! on 23 Feb 2021
Commented: Hmm! on 1 Mar 2021
I have a complex number in a vector,
e =
-0.0000
3.0000
9.0000
>> logical(e) %checking if the the first entry is actually 0. Results show it is not
ans =
3×1 logical array
1
1
1
>> t = sqrt(e) % sqauring the entries shows all the three entries are complex numbers
t =
0.0000 + 0.0000i
1.7321 + 0.0000i
3.0000 + 0.0000i
L = logical(t) % In Matlab documentation it not possible to use logical for complex numbers
Error using logical
Complex values cannot be converted to logicals.
>> t(1,1)==0 % checking if the first entry is actually 0?
ans =
logical
0
>> t(1,1)<0 % checking if the first entry is actually less than 0?
ans =
logical
0
>> t(1,1)>0 % checking if the first entry is actually greater than 0?
ans =
logical
0
% QUESTION: is there a way to compare t(1,1) with 0 to know whether is it 0 or not?
% Alternatively: What is the genral way of using logicals for complex numbers?

Walter Roberson on 26 Feb 2021
e = [-1e-9;3;9;0]
e = 4×1
-0.0000 3.0000 9.0000 0
t = sqrt(e);
[real(t), imag(t)]
ans = 4×2
0 0.0000 1.7321 0 3.0000 0 0 0
t == 0
ans = 4x1 logical array
0 0 0 1
format long g
e
e = 4×1
-1e-09 3 9 0
[real(t), imag(t)]
ans = 4×2
0 3.16227766016838e-05 1.73205080756888 0 3 0 0 0
You are being mislead by your default output format. If you switch output formats you will be able to see quickly that your e(1) is a small negative value.
You can see that t == 0 is enough to compare both parts of a complex number to 0, and correspondingly,
Lt = t ~= 0
Lt = 4x1 logical array
1 1 1 0
is the equivalent of logical()

### More Answers (2)

Image Analyst on 27 Feb 2021
Perhaps this:
complexVector =[
0.0000 + 0.1000i
1.7321 + 0.0010i
3.0000 + 0.0000i]
% Define a tolerance:
tolerance = 0.01
% Find out which elements have an imaginary magnitude less than tolerance:
belowTolerance = imag(complexVector) < tolerance
% For those elements with an imaginary value below the tolerance,
% turn them into a real number with no imaginary component.
complexVector(belowTolerance) = real(complexVector(belowTolerance))
You get:
complexVector =
0 + 0.1i
1.7321 + 0.001i
3 + 0i
tolerance =
0.01
belowTolerance =
3×1 logical array
0
1
1
complexVector =
0 + 0.1i
1.7321 + 0i
3 + 0i
Note the second and third elements are real, not complex, numbers because the imaginary part was stripped off.
##### 1 CommentShowHide None
Hmm! on 1 Mar 2021
You're also right. Thanks for the help

David Hill on 23 Feb 2021
%depends on what you are trying to compare
real(t)==0;
imag(t)==0;
norm(t)==0;
Hmm! on 27 Feb 2021
You're right.

R2020b

### Community Treasure Hunt

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

Start Hunting!