Archive for the ‘MATLAB’ category

3D Hill Plot with MATLAB

July 27th, 2010

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.

exp(-(x.^2)-(y.^2)) + 0.5.*exp(-((x-2).^2)-(y.^2));

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

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.

plot(x,h([1,10,20],:)); % plot 1st, 10th and 20th values of y
title('2D Hill Plot'); % title and axis labels
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.

Create Fractals with MATLAB

July 26th, 2010

As part of my University course we had to use the scientific MATLAB programming language, and computing environment,  for several tasks in the first year. While the set tasks were as drab and dreary as you would expect from a Physics course, it taught us the basic skills and the problem solving skills key to the course.

In my spare time I ported a PHP script my friend created to MATLAB which enables the creation of beautiful fractals from the Mandlebrot set. The maximum image size you can create depends on the amount of memory available in your system and the script isn’t something I’ve spent a lot of time on so feel free to improve on it.

On my laptop, a 10,000 x 10,000 pixel image took about an hour to create, using 20 iterations. You may find this differs on other machines.

Download the MATLAB Fractal Generator Code.