MEX usage of mldivide() produces incorrect/different results
3 views (last 30 days)
Show older comments
I have used the coder toolkit to create a MEX'ed version of the matrix exponential function. Everything up until the point of the matrix division is equivalent. However, once it arrives at this line of code:
F = (V-U)\(2*U) + I;
The result of the function becomes inaccurate. Although the values are small, the percent change from the expected (non-mex) answer can reach up to over 100%.
Why is this discrepancy happening, and what can I do to fix this so that, while the answers don't have to be equivalent, the percent change from the actual answer must be at an acceptable level?
Or perhaps there is another method to solve the equation without the use of "\". Note: I have already tried the inv(A)*B method.
*I have provided a test case in the comments section.
6 Comments
John
on 16 Oct 2014
Ahh thanks, that is helpful!
I had to code a replacement for mldivide for some code and I chose to use Gaussian Elimination and then back substitution. The Flow chart Matt provided should give you more directions towards what linear equation solvers would best fit your needs.
Accepted Answer
Sean de Wolski
on 16 Oct 2014
The results are expected. If we look at the difference between F and Fmex it’s 2*eps(F)
eps(max(F(:)))
ans =
4.4409e-16
norm(F-mex_F)
ans =
9.9491e-16
Since some values in F are exactly 0:
any(F(:)==0)
ans =
1
Dividing by these will yield either nan (0/0) or +-inf (anything else/0).
The fair "percentage test" would be:
100*norm(F-mex_F)/norm(F)
ans =
3.1797e-14
Which is very small.
More Answers (1)
Matt J
on 16 Oct 2014
Edited: Matt J
on 16 Oct 2014
It is generally not realistic to expect low percent error in two floating point calculations meant to result in zero or something close to zero. There are so many ways in floating point math that things meant to result in zero can cancel imperfectly, e.g.,
>> x=[1.1.^(0:4) , -1.1.^(4:-1:0)]
x =
1.0000 1.1000 1.2100 1.3310 1.4641 -1.4641 -1.3310 -1.2100 -1.1000 -1.0000
>> sum(x) %supposed to be zero
ans =
1.3323e-15
and obviously any such error relative to zero is going to be Inf percent.
2 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!