Functions Demo Filled
Functions Demo Filled
x = linspace(0,5,100);
y = exp(x);
figure
plot(x,y)
title('f(x)=e^x')
xlabel('x')
ylabel('y')
% z = x*y;
% uncomment the above line of code to see an error message
1
Notice right away we get an error. What happened? Well, it is important to recall that x and y are row vectors
Multiplication of two row vectors has no mathematical meaning. Aside: multiplying a row vector times a column
vector is like taking the dot-product of the two vectors, and multiplying a column vector by a row vector creates
a matrix.
What we really want to do is plot a vector of values versus a vector of x values. To do so, we evaluate
element-wise by putting a "." before the multiplication operation:
z = x.*y;
figure
plot(x,z)
title('f(x)=xe^x')
xlabel('x')
ylabel('f(x)')
Note the use of Latex in the labeling and throughout this document. While not a requirement, the font and
syntax of Latex are commonplace for scientific writing and can help make your documents look more elegant.
We will learn some of the basics later on, and if you are curious there are countless resources online.
2
% f = @(x) x*exp(x) won't work since you need to account for element-wise
% operations
f = @(x) x.*exp(x)
We have created our own function handle. Note that we include the "." before the multiplication symbol. This is
a very important detail, since we want to be able to input vectors into our function. Now, to plot, it is quite
straightforward:
z = f(x)
z = 1×100
0 0.0531 0.1117 0.1763 0.2472 0.3251 0.4103 0.5035
plot(x,f(x))
title('f(x) = xe^x')
xlabel('x')
ylabel('f(x)')
g = @(x) x.^2
3
@(x)x.^2
h = @(x) 20*x./exp(x)
figure
plot(x,g(x))
hold on
plot(x,h(x))
legend('g(x)','h(x)')
xlabel('x')
To plot multiple curves on the same plot, one must enter "hold on" in between the lines which plot the curves.
Note that when defining , we do not need to use element-wise multiplication with the scalar value . As
you learned in Calc 3, multiplying a vector by a scalar is well-defined mathematically. Also note the addition of a
legend, which will come in handy later on.