MATLAB Answers

Double precision changes to complex double after calculation

124 views (last 30 days)
mashtine
mashtine on 30 Jan 2015
Commented: Guillaume on 30 Jan 2015
Hi everyone,
I have a matrix with very simple data in double precision but after doing a calculation (listed below) some of the numbers, not all, change to complex numbers. Even the timestamp which is not used in the calculation changes to complex. The data that changes appears to be the same as the data that doesn't change.
Any ideas?
for i = 1:length(ws);
if L(i,1) >= -500 && L(i,1) <= -12
wsstd_uns(i,1) = timestamp(i,1);
wsstd_uns(i,2) = fric(i,1).*(0.35*((-(BLH(i,1)./(vK.*L(i,1)))).^(2/3)) + (2 -(10./BLH(i,1)))).^(1/2);
wsstd_uns(i,3:5) = [ws(i,1),wgst(i,1),(wgst(i,1)-ws(i,1))];
elseif L(i,1) >= 0 && L(i,1) <= 500
wsstd_s(i,1) = timestamp(i,1);
wsstd_s(i,2) = 2.*fric(i,1).*((1 -(10./BLH(i,1))).^(1/2));
wsstd_s(i,3:5) = [ws(i,1),wgst(i,1),(wgst(i,1)-ws(i,1))];
end
end
  2 Comments
Guillaume
Guillaume on 30 Jan 2015
Actually, as per the tip section of the doc you've linked:
  • Since i is a function, it can be overridden and used as a variable. However, it is best to avoid using i and j for variable names if you intend to use them in complex arithmetic.
  • For speed and improved robustness in complex arithmetic, use 1i and 1j instead of i and j.
In other words, unless you use i or j as the imaginary unit, it doesn't matter. And if you do use i or j as the imaginary unit, you shouldn't and should use 1i or 1j instead (which can't be used as a variable).

Sign in to comment.

Accepted Answer

Andreas Goser
Andreas Goser on 30 Jan 2015
Theory one: You use i as a variable. As this is a "reserved word" for complex calculations, there may be an unexpected effect.
Theory two: One of your functions or variables shadows the real MATLAB command and does something unexpected. Like you would assign plot=1 the then try to use the plot command.
  1 Comment
mashtine
mashtine on 30 Jan 2015
Two good theories. Finding the root issue is the problem but thanks Andreas. I think I will just use real() to eliminate the imaginary values as they are 0 anyways.

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 30 Jan 2015
Well, you take the square root and cubic roots of some numbers so, if these numbers are negative, you'll get some complex numbers.
As for your timestamp, are you sure it's complex, that is imag(x) ~= 0. The real numbers in a matrix containing complex numbers are displayed as complex but with an imaginary part equal to 0.
  4 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!