# 3D Hill Plot with MATLAB

July 27th, 2010 by Sunny Man

I thought I’d share some of the easier things I had to do as part of the first year of my course. One of those tasks was to generate a 3D plot of a function and then also plot 2D cross sections at different values.

We start off with a mathematical function that describes, what we will call, our hill. This function represents the ‘height’ of our hill, h if you will, at the different points in x and y.

So, in our MATLAB script we first of all generate a grid of points using x values from -1.5 to 3.5 and y values from -2 to 2. The follow codeĀ achievesĀ this.

```x = linspace(-1.5,3.5,50); % 50 values of x y = linspace(-2,2,25); % 25 values of x [xg yg] = meshgrid(x,y); % generate points```

And next we generate the height values of our hill, using the grid we have just created with x -> xg and y ->yg.

`h = exp(-(xg.^2)-(yg.^2)) + 0.5.*exp(-((xg-2).^2)-(yg.^2)); % calculate height values`

With our hight values in the array h, all we need to do now is plot them. Firstly, to create the 3D plot we just plot x,y and h using the surf() function.

```figure(1); % create new figure window surf(x,y,h); % surface plot title('3D Hill Plot'); % title and axis labels xlabel('x'); ylabel('y'); zlabel('height');```

Now, to look at several slices through the hill at different values of y, we need to select the different values of y from its array and plot them on the same graph.

```figure(2); plot(x,h([1,10,20],:)); % plot 1st, 10th and 20th values of y title('2D Hill Plot'); % title and axis labels xlabel('x'); ylabel('height'); legend('y = -1.5','y = -0.4','y = 1.2',0); % legend not overlapping any of the plot```

Putting it all together you get a 3D plot of the function and the cross sections in two windows. Job done.