plotDecisionBoundary.m 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. function plotDecisionBoundary(theta, X, y)
  2. %PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
  3. %the decision boundary defined by theta
  4. % PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the
  5. % positive examples and o for the negative examples. X is assumed to be
  6. % a either
  7. % 1) Mx3 matrix, where the first column is an all-ones column for the
  8. % intercept.
  9. % 2) MxN, N>3 matrix, where the first column is all-ones
  10. % Plot Data
  11. plotData(X(:,2:3), y);
  12. hold on
  13. if size(X, 2) <= 3
  14. % Only need 2 points to define a line, so choose two endpoints
  15. plot_x = [min(X(:,2))-2, max(X(:,2))+2];
  16. % Calculate the decision boundary line
  17. plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));
  18. % Plot, and adjust axes for better viewing
  19. plot(plot_x, plot_y)
  20. % Legend, specific for the exercise
  21. legend('Admitted', 'Not admitted', 'Decision Boundary')
  22. axis([30, 100, 30, 100])
  23. else
  24. % Here is the grid range
  25. u = linspace(-1, 1.5, 50);
  26. v = linspace(-1, 1.5, 50);
  27. z = zeros(length(u), length(v));
  28. % Evaluate z = theta*x over the grid
  29. for i = 1:length(u)
  30. for j = 1:length(v)
  31. z(i,j) = mapFeature(u(i), v(j))*theta;
  32. end
  33. end
  34. z = z'; % important to transpose z before calling contour
  35. % Plot z = 0
  36. % Notice you need to specify the range [0, 0]
  37. contour(u, v, z, [0, 0], 'LineWidth', 2)
  38. end
  39. hold off
  40. end