Search code examples
matlabmatlab-figure

How to plot 2D quadratic function as a contour


I'm trying to replicate the following plot in Matlab, minus the zigzagging line.

enter image description here

I know that this is a two-dimensional quadratic function y = x1^2 + 10 * x2^2.

My best attempt is with

fcontour(@(x1, x2) x1.^2 + 10*x2.^2)
xlim([-60, 60])
ylim([-60, 60])

but this results in a graph like this:

enter image description here

In another attempt, I save the contour plot and set the range on it as follows:

handle = fcontour(@(x1, x2) x1.^2 + 10*x2.^2)
handle.YRange = [-60, 60]
handle.XRange = [-60, 60]

This results in a slightly better plot colorwise, but it's still not right.

enter image description here

How do I fix my code to arrive at the first plot?


Solution

  • Use contour instead of fcontour, it gives you better control on the number of contour lines:

    steps = -60:60;
    [x1, x2] = meshgrid(steps, steps);
    fx = x1.^2 + 10*x2.^2;
    contour(x1, x2, fx, 40);
    colormap jet
    

    But if you insist to use fcontour, you need to prepare list of levels of contour lines first:

    dim = 60;
    f = @(x1, x2) x1.^2 + 10*x2.^2;
    levels = linspace(0, f(dim, dim), 40);
    fcontour(f, [-dim, dim], 'levellist', levels);
    colormap jet
    

    enter image description here