Search code examples
matlabmatlab-figure

Plotting an implicit function in Matlab


I have a function of 4 variables, let us say $f(x,t,w,n)$, the function $g(x,n)$ is defined as

g(x,n)=\int_a^b\int_c^d f(x,t,w,n) dt dw

where $a$, $b$, $c$, $d$ are given constants and the integral cannot be explicitly computed in a closed form. Then, $h(x,n)$ is given by

h(x,n)=\ln\frac{g(x,n)}{g(-x,n)}

I want to ploy $y=h(x,n)$ as a function of $x$ for different values of $n$ on the same plot. How can I do this. If it helps, $f(x,t,w,n)$ is of the following form

f(x,t,w,n)=\exp{-\frac{x^2+tw+wx}{n}}+\exp{-\frac{t^2+tx^2-2tx}{2n}}

Solution

  • I think this probably does what you want. I specify f, g, and h as anonymous functions and use the quad2d to estimate the value of the double integral.

    %% Input bounds
    a = 0;
    b = 1;
    c = 0;
    d = 2;
    
    %% Specify functions
    
    % vectorize function as a prerequisite to using in quad2d
    f = @(x,t,w,n) exp( -(x.^2 + t.*w + w.*x)./n) + exp(-(t.^2 + t.*x.^2 - 2.*t.*x)./(2.*n));
    
    % keeps x,n fixed in function call to f(...), varies a < t < b; c < w < d
    g = @(x,n) quad2d(@(t,w) f(x, t, w, n), a, b, c, d);
    
    % wrap functions into h
    h = @(x,n) log(g(x,n)/g(-x,n));
    
    %%
    
    figure();
    hold on % keep lines
    
    x_range = linspace(-1,1);
    
    for n = 1:5
        plotMe = zeros(1, length(x_range));
        for iter = 1:length(x_range)
            plotMe(iter) = h(x_range(iter), n);
        end
    
        lineHandle(n) = plot(x_range, plotMe);
    end
    
    
     legend(lineHandle, {
         ['N: ', num2str(1)],...
         ['N: ', num2str(2)],...
         ['N: ', num2str(3)],...
         ['N: ', num2str(4)],...
         ['N: ', num2str(5)]...
         }...
     )