除非写入全局变量,否则ezplot不工作

时间:2015-01-04 18:06:30

标签: matlab plot

我试图绘制以下功能

% k-nn density estimation
% localSearcher is a handle class responsible for finding the k closest points to x
function z = k_nearest_neighbor(x, localSearcher)            

    % Total point count
    n = localSearcher.getPointCount();

    % Get the indexes of the k closest points to x
    % (the k parameter is contained inside the localSearcher class)
    idx = localSearcher.search(x);

    % k is constant
    k = length(idx);  

    % Compute the volume (i.e. the hypersphere centered in x that encloses every
    % sample in idx)
    V = localSearcher.computeVolume(x, idx);

    % The estimate for the density function is p(x) = k / (n * V)        
    z = k / (n * V); 

end

我确信上述算法是正确的,因为我使用以下函数得到了合理的图

% Plot the values of k_nearest_neighbor(x, searcher) by sampling it manually
function manualPlot(samples, searcher)

    a = -2;
    b = 2;
    n = 1000;
    h = (b - a) / n;
    sp = linspace(a, b, n);
    pt = zeros(n);
    areas = zeros(n);
    estimated_pdf = @(x)k_nearest_neighbor(x, searcher);  
    area = 0;
    for i = 1 : length(sp)
        x = sp(i);        
        pt(i) = estimated_pdf(x);

        area = area + h * pt(i);
        areas(i) = area;
    end

    figure, hold on  
    title('k-nn density estimation');
    plot(sp, pt, sp, areas, ':r');
    legend({'$p_n(x)$', '$\int_{-2}^{x} p_n(x)\, \, dx$'}, 'Interpreter', 'latex', 'FontSize', 14);
    plot(samples,zeros(length(samples)),'ro','markerfacecolor', [1, 0, 0]);    

    axis auto
end

通过

调用
 function test2()

    clear all
    close all

    % Pattern Classification (page 175)
    samples = [71 / 800; 128 / 800; 223 / 800; 444 / 800; 475 / 800; 546 / 800; 641 / 800; 780 / 800];

    % 3-nn density estimation
    searcher = NaiveNearestSearcher(samples, 3); 
    manualPlot(samples, searcher);    
 end

输出

Manually sampling the anonymous function works flawlessly

但是,如果我尝试用ezplot

做同样的事情
% Plot the values of k_nearest_neighbor using ezplot
function autoPlot(samples, searcher)

    estimated_pdf = @(x)k_nearest_neighbor(x, searcher);    

    figure, hold on    
    ezplot(estimated_pdf, [-2,2]);
    title('k-nn density estimation');
    legend({'$p_n(x)$', '$\int_{-2}^{x} p_n(x)\, \, dx$'}, 'Interpreter', 'latex', 'FontSize', 14);
    plot(samples,zeros(length(samples)),'ro','markerfacecolor',[1,0,0]);    

    axis auto
end

我收到以下不正确的结果

ezplot doesn't work

控制台没有发出警告 它类似于传递给匿名函数的searcher参数

estimated_pdf = @(x)k_nearest_neighbor(x, searcher);    
ezplot(estimated_pdf, [-2,2]);

超出范围" ({1}}终止前的(或其他) 真正奇怪的是添加

ezplot

显然解决了问题(!) 这是完整的source code,我使用的是MATLAB R2011a。

0 个答案:

没有答案