MEX usage of mldivide() produces incorrect/different results
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
Sean de Wolski
on 15 Oct 2014
How far off is it relatively?
I personally use this as a tester for MATLAB Coder generated MEX files:
% Unit test object
Tester = matlab.unittest.TestCase.forInteractiveUse;
% Assert within tolerance
assertEqual(Tester,foo(inputs),foo_mex(inputs),'RelTol',10^-15)
Garren
on 16 Oct 2014
John
on 16 Oct 2014
you could always use a Gaussian elimination function since I am pretty sure mldivide uses some sort of Gaussian elimination method in it.
since I am pretty sure mldivide uses some sort of Gaussian elimination method in it.
No, it does not. See the flowcharts under Algorithm for Full Inputs and Algorithm for Sparse Inputs at
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
More Answers (1)
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
Categories
Find more on Creating and Concatenating 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!