mat2str() on complex values with 0 inaginary part
3 views (last 30 days)
Show older comments
Hi,
Tried mat2str(complex(5,6)) witch seems ok:
ans =
'5+6i'
But other complex values with imaginary part 0 or 0+0i are printed as real values:
mat2str(complex(5,0))
ans =
'5'
mat2str(0+0i)
Seems incorect to me, is this a bug ?
0 Comments
Accepted Answer
Jan
on 26 Jan 2021
Edited: Jan
on 26 Jan 2021
Mathematically 5 is the same as 5+0i, so the output is correct.
So omitting the imaginary part is a question of taste.
If you want to display it, do this expliticitly:
x = 1 + 2i;
sprintf('%g %gi', real(x), imag(x))
Alternatively you can copy the code of mat2str to e.g. mat2stri anywhere in your user-defined folders in the path and remove the line:
imagStr(imagVal == 0) = "";
0 Comments
More Answers (2)
Steven Lord
on 26 Jan 2021
Not a bug. Many operations in MATLAB, if the result has an all zero imaginary part, will remove that imaginary part. complex is one of the few operations that does not by design.
x = complex(5, 0)
y = x(1)
z = x + 0
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!