绘制等高线:contour
网状图绘制:surf
如下画网状图surf:
%% ============= Part 4: Visualizing J(theta_0, theta_1) =============
fprintf('Visualizing J(theta_0, theta_1) ...\n')
theta0_vals = linspace(-10,10,100);
theta1_vals = linspace(-1,4,100);
J_vals = zeros(length(theta0_vals),length(theta1_vals));
m = length(X);
for i = 1:length(theta0_vals)
for j = 1:length(theta1_vals)
t = [theta0_vals(i);theta1_vals(j)];
J_vals(i,j) = 1/(2*m)*sum((X*theta - Y).^2);
end
end
figure;#指定不同的图
% Because of the way meshgrids work in the surf command, we need to
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
surf(theta0_vals,theta1_vals,J_vals);
如下画等高线图contour:
figure;
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20));#J_vals是转置过后的
xlabel('theta_0'); ylabel('theta_1');
hold on;
plot(theta(1),theta(2),'rx','MarkerSize', 10, 'LineWidth', 2);
网状图与等高线同时绘制
在某个情境下,可出现如下运行结果: