Converting some matlab to C (or C++)

2 views (last 30 days)
Gilbert S
Gilbert S on 12 Feb 2015
Commented: Gilbert S on 12 Feb 2015
Hi there,
I have been working through the Matlab function fir2 -
I'm converting it to C++ line by line.
I'm currently at the following section in the m-file where it performs the Fourier Time Shift -
% Fourier time-shift.
dt = 0.5 .* (nn - 1) rad = -dt .* sqrt(-1) .* pi .* (0:npt-1) ./ (npt-1);
I can find dt, ok.
But for rad, I'm getting 'NaN', due to the sqrt(-1) operation. So I'm thinking I need to be handling the imaginary \ complex number here with something like std::complex
I'm reading this part of the matlab code as something equivalent to this in C -
!!! Please see attached file as I couldnt write formatted C++ code here.. Thanks !!!
The C++ output looks ok for the imaginary part, but the real part is non zero, and also negative. So I must be doing something wrong here..
Any ideas?
Thanks in advance
  2 Comments
Adam
Adam on 12 Feb 2015
What does sqrtMinusOne output as in debug?
Is it precisely 0 - 1i?
If not then I assume the error is just a rounding error, but otherwise it is hard to see why it is non-zero with only multiplication operations.
It is a while since I used std::complex so I assume it overloads multiplication by a double otherwise your code just wouldn't compile anyway!
Gilbert S
Gilbert S on 12 Feb 2015
Hi Adam,
Thanks for the reply. If I debug the sqrtMinusOne it is coming out as -
real : 0.00000000000000006123 imag : 1.00000000000000000000
Thats with the debug set to show up to 20 significant digits.
So that looks like a clue, the real part should be completely zero. I may have to initialize the complex differently..

Sign in to comment.

Accepted Answer

Adam
Adam on 12 Feb 2015
"What does sqrtMinusOne output as in debug?
Is it precisely 0 - 1i?
If not then I assume the error is just a rounding error"
I added my comment as an Answer since it seems to point correctly to the problem, together with the further obvious comment below in response to your reply.
Yeah, that will be the reason then because all those multiplications that you then do will increase that error. It is still a small error which is insignificant in real terms, but depending what you intend to do with the result the fact that it isn't precisely 0 could be a problem.
Since you know what sqrt(-1) is though you should just hard-code it as 0 -1i in your std::complex. No point taking the processing time to do a calculation with error when you could just hard-code it precisely!
  1 Comment
Gilbert S
Gilbert S on 12 Feb 2015
Thats a good suggestion about initialization.. I think thats the issue..
Thanks

Sign in to comment.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!