Saturday, April 16, 2016

Basic 2D, 3D Function Plotting in Matlab

There are a number of ways you can plot a function in matlab. Let's see some examples:

1. Let's start with one variable. Plot of the function $f(x) = x^2 -3$ would be:
fplot(@(x) x^2 - 3, [-5 5]) //fplot requires limits

2. Plotting the sum of the outcomes of two dice throw:
We know that the outcome of a dice throw is uniformly distributed over the range [1,6]. So the sum of the outcomes should be in the range [2, 12]. If we continue this experiment many times, we will start to notice that the output is not uniformly distributed, it's actually normal. We can see the simulation by running the command :
hist(randi([1 6], 1, 10000)+randi([1 6], 1, 10000))%adding two uniformly distributed r.v of the range(1,6) 10000 times
Which should produce an image resembling a normal distribution:

2. Drawing a circle from the equation ( $x^2 + y^2 = 5^2 $):
f = @(x) sqrt(5^2 - x.^2)
fplot(@(x) sqrt(5^2 - x.^2), [-5 5])
hold on
fplot(@(x) (-1)*sqrt(5^2 - x.^2), [-5 5])
hold off
axis equal %to preserves axis ratio, else would end up looking like an ellipse 


3. Let's consider a function $z = x^2 + y^2$, for a range of values of x and y:
[x, y] = meshgrid(linspace(-10, 10, 100), linspace(-10, 10, 100))
z = x.^2 + y.^2
mesh(x,y,z)


4. Another example:
[x, y] = meshgrid(linspace(-10, 10, 100), linspace(-10, 10, 100))
xcosx = x.*cos(x)
ysiny = y.*sin(y)
z = xcosx' * ysiny
surfc(x, y , z)

No comments:

Post a Comment