Using contour to plot function

2019-09-17 20:35发布

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?

3条回答
女痞
2楼-- · 2019-09-17 21:04

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)
查看更多
孤傲高冷的网名
3楼-- · 2019-09-17 21:07

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:

enter image description here

查看更多
Fickle 薄情
4楼-- · 2019-09-17 21:07

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))

ContourPlot

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
查看更多
登录 后发表回答