Problem graphing the % error between a real function and its linearization using contourf in MATLAB
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Luis
el 7 de Mzo. de 2025
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 comentarios
Respuesta aceptada
Stephen23
el 7 de Mzo. de 2025
Editada: Stephen23
el 7 de Mzo. de 2025
"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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Contour Plots en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


