MATLAB - 在 meshgrid 中的每个点评估函数?

MATLAB - Evaluate a function at each point in meshgrid?

我想绘制双变量(独立)高斯分布的热图。为了在二维正方形上绘制它,我做了

joint_pdf = @(m, s) normpdf(m, 1, 1)*normpdf(s, 1, 1);
[x, y] = meshgrid(0:0.1:10, 0:0.1:10);
prob_map = zeros(numel(x), numel(y));
for idx1 = 1:size(prob_map, 1)
    for idx2 = 1:size(prob_map, 2)
        prob_map(idx1, idx2) = joint_pdf(x(idx1), y(idx2));
    end
end
image(prob_map);

这非常非常慢。有没有办法避免循环?

可以侵入 normpdf.m 并在 vectorized manner and thus also avoid those many function calls, which must make it much more efficient. I like to call this hacked approach as using the "raw version" of normpdf' 的实现中获取 prob_map 的所有元素。这是最终代码 -

%// Define arrays for inputting into meshgrid
array1 = 0:0.1:10;
array2 = 0:0.1:10;
[x, y] = meshgrid(array1, array2);

%// Define parameteres for normpdf
mu = 1;
sigma = 1;

%// Use "raw version" of normpdf to calculate all prob_map elements in one go
dim1 = exp(-0.5 * ((x(:) - mu)./sigma).^2) ./ (sqrt(2*pi) .* sigma);
dim2 = exp(-0.5 * ((y(:) - mu)./sigma).^2) ./ (sqrt(2*pi) .* sigma);
prob_map = bsxfun(@times,dim1,dim2.');

如果您有兴趣进一步加快速度,可以分别在 dim1dim2 中预先计算更多围绕 x(:)y(:) 的内容!