Converting some matlab to C (or C++)
2 views (last 30 days)
Show older comments
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
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!
Accepted Answer
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!
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown 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!