问题
I try to use contour to plot this function
3y + y^3 - x^3 = 5
I try contour(3*y+y^3-x^3-5) but it doesn't work.
How can I use contour to plot this function?
回答1:
Are x and y properly defined as 2x2 matrices? If so then the "power" operator needs to be done on a component-wise basis (.^3 instead of ^3).
This works:
[x,y] = meshgrid(-2:.2:2,-2:.2:2);
contour(3*y+y.^3-x.^3-5)
回答2:
Maybe you can try fcontour
, which plots the contour lines of the function z = f(x,y) for constant levels of z over the default interval [-5 5] for x and y.
f = @(x,y) 3*y + y.^3 - x.^3 - 5;
fcontour(f)
Output:
回答3:
I'm not convinced this addresses all parts of your question but it's a start. If you absolutely want contour
to call a function, you can adjust my example to contour(X,Y,fh(X,Y))
.
Better Approach
fh=@(x,y) 3*y + y.^3 - x.^3 -5; % <--- This is your function
x = (-4:.25:4)';
y = (-2:.25:2)';
[X,Y] = meshgrid(x,y);
Z = fh(X,Y);
contour(X,Y,fh(X,Y))
The Direct Approach (not preferred but works)
Notice the Z
is transposed to make this work.
fh=@(x,y) 3*y + y.^3 - x.^3 -5; % <----this is your function
X = (-4:.25:4)';
Y = (-2:.25:2)';
Z = zeros(length(X),length(Y));
for i = 1:length(X)
for j = 1:length(Y)
xi = X(i);
yj = Y(j);
Z(i,j) = fh(xi,yj);
end
end
contour(X,Y,Z','LevelList',-60:10:60,'ShowText','on','LineWidth',1.4) % Fancied it up a bit
来源:https://stackoverflow.com/questions/18517933/using-contour-to-plot-function