Reputation: 20365
I wish to plot the heat map of a bivariate (independent) Gaussian. To plot it over a 2D square, I did
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);
This is very very slow. Is there a way of avoiding the looping?
Upvotes: 1
Views: 1069
Reputation: 221624
One can hack into normpdf.m
and get all the elements of prob_map
in a 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
's implementation. Here's the final code -
%// 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.');
If you are interested in further speeding it up, you can pre-calculate few more stuffs surrounding the x(:)
and y(:)
in dim1
and dim2
respectively!
Upvotes: 2