Imaginary Number Notation/ Formatting Real and Complex Results

Illustration
Mia - 2020-12-10T09:53:15+00:00
Question: Imaginary Number Notation/ Formatting Real and Complex Results

I am performing an eigenvalue calculation for a range of 10 numbers. One of these numbers are negative which results in a complex eigenvalue but the remainder are real numbers. I want to display these to the screen as results, however, when I do this the notation for the real values solutions occur as, for example, "3.464+0i" when it should just be "3.464". My 9th element in the calculation appears as how I want it "0+6.0598e-09i" and I would like to keep it this way. Is there a solution to this or do I just have to deal with the formatting?

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

You can format the display of real and complex numbers in MATLAB to achieve the desired appearance by checking if the imaginary part of a number is zero. If the imaginary part is zero (within a tolerance for numerical precision), display only the real part. Otherwise, display the full complex number.

Here's an example of how you can format your results:

Code Example:

 

% Example eigenvalue calculation
eigenvalues = [3.464 + 0i, 0 - 6.0598e-09i, -1 + 1i, 2 + 0i]; % Example data

% Set a tolerance for considering imaginary part as zero
tolerance = 1e-10;

% Loop through the eigenvalues and display them
for i = 1:length(eigenvalues)
    real_part = real(eigenvalues(i));
    imag_part = imag(eigenvalues(i));
    
    % Check if the imaginary part is effectively zero
    if abs(imag_part) < tolerance
        fprintf('Eigenvalue %d: %.4f\n', i, real_part); % Display real part only
    else
        fprintf('Eigenvalue %d: %.4f%+.4fi\n', i, real_part, imag_part); % Display full complex number
    end
end

Explanation

  1. Tolerance: A small value (1e-10 in this case) is used to handle floating-point precision errors. Imaginary parts smaller than this value are treated as zero.
  2. Condition: The code checks if abs(imag_part) < tolerance. If true, only the real part is displayed.
  3. Formatting:
    • Real numbers are formatted as %.4f.
    • Complex numbers are formatted as %.4f%+.4fi to include both real and imaginary parts with appropriate signs.

Output

For the example eigenvalues:

 

Eigenvalue 1: 3.4640
Eigenvalue 2: 0.0000-0.0000i
Eigenvalue 3: -1.0000+1.0000i
Eigenvalue 4: 2.0000

This approach ensures that real numbers are displayed without the "+0i", while complex numbers retain their full notation.


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!