Problem graphing the % error between a real function and its linearization using contourf in MATLAB
2 次查看(过去 30 天)
显示 更早的评论
I am trying to visualize the percentage error between a real function and its linearized version in a contour map (contourf). I have defined my reference variables and calculated the relative error as:

Where:
- g = X./Y is the real function.
- z is the linearized function
- Xref = 5, Yref = 4 are the references.
The code I am using is the following:
Xref = 5;
Yref = 4;
[X,Y] = meshgrid(linspace(0,10,50),linspace(3,5,50));
g = X./Y;
z = Xref/Yref+1/Yref*(X-Xref)-Xref/Yref.^2*(Y-Yref);
surf(X,Y,g,"FaceColor","#EDB120","LineStyle","none")
hold on
surf(X,Y,z,"FaceColor","#0072BD","LineStyle","none")
xlim([0 10])
ylim([3 5])
zlim([-0.5 3.5])
box on
legend("g=X/Y","Linearized")
xlabel("X(t)")
ylabel("Y(t)")
zlabel("g=X/Y")
hold off
% Error Graph (%)
Error3 = abs(z-g)./g*100;
contourf(X, Y, Error3)
xlabel("X(t)")
ylabel("Y(t)")
The result I should get would look like this:

I think the problem is the way I'm calculating the %Error between those two functions rather than how I'm using the contourf function, but i don't know.
0 个评论
采纳的回答
Stephen23
2025-3-7
编辑:Stephen23
2025-3-7
"I think the problem is the way I'm calculating the %Error between those two functions..."
That is the problem, because you are dividing by very small values in g, so of course the relative error ends up being quite large. In fact the smallest absolute value in g is zero: how many percent of zero is any finite value of z? (hint: infinite). So in the worst case, those "relative error" values blow up to infinity:
Xref = 5;
Yref = 4;
[X,Y] = meshgrid(linspace(0,10,50),linspace(3,5,50));
g = X./Y;
z = Xref/Yref+1/Yref*(X-Xref)-Xref/Yref.^2*(Y-Yref);
mnz = min(abs(z(:)))
mng = min(abs(g(:)))
mnz./mng
This is not a MATLAB problem, this is a conceptual problem: first answer the question "how many times greater than zero is zero point zero zero six four?" then you can plot your "relative error" calculation.
Plotting the absolute error is much simpler:
E = abs(z-g);
contourf(X,Y,E)
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Contour Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!