function rbgrad(n)

% Plots Rosenbrock's function with a colormap 
% indicating local magnitude of the gradient.
%
% Zero magnitudes are mapped to the lowest color 
% in the colormap and magnitudes of n and above 
% are mapped to the highest color in the colormap.
%
% For small n, decrease the step size on x and y.

x = -2:0.01:2;
y = -1:0.01:3;
[X, Y] = meshgrid(x, y);

Z = 100.*(Y-X.^2).^2 + (1-X).^2;

% Analytic gradient and magnitude:
g1 = 400*X.^3 - 400*X.*Y + 2*X - 2*ones(size(X));
g2 = 200*Y - 200*X.^2;
M = sqrt(g1.^2 + g2.^2);

% Plot:
surf(X, Y, Z, M)
shading interp
set(gca, 'clim', [0, n])
colorbar
title('Rosenbrock''s Function: Gradient Magnitudes')

clear x y X Y Z g1 g2 M