The statement of the exercise is this one:
And the solutions is this one:
I can not understand how the function was evaluated for f=2
and f=3
. Why is it evaluated as f(21)
and not f(2)
?
The statement of the exercise is this one:
And the solutions is this one:
I can not understand how the function was evaluated for f=2
and f=3
. Why is it evaluated as f(21)
and not f(2)
?
linspace(a,b)
creates an array spanning from a
to b
in 100 points, so linspace(0,3)
creates an array [0/33 1/33 2/33, ... 98/33 99/33]
whereas
x = 0:0.1:3
creates an array [0 0.1 0.2 0.3 ... 2.9 3]
, i.e. from 0
in steps of 0.1
to 3
.
f = x.^3.*cos(x+1)
then calculates for each value contained in the array x
the value of xi^3*cos(xi+1)
, where xi
is the i-th element. So f
will also have 31 elements. The 21st element, which is 2
, will evaluate the function for f = 2^3*cos(2+1)
.
To explicitly show this you could use
f(x==2)
which will give you the same answer as f(21)
. Numerical equality not guaranteed, use abs(x-2)<eps
or similar for stability
Note that you could have evaluated the function on x=2
and x=3
as well using the 'old' version of x
, since x(67)==2
and x(100)==3
.
An alternative to create the array with steps of 0.1
is using linspace(0,3,31)
, which creates a linearly spaced array starting at 0
, ending at 3
and having 31
equally spaced steps. This is useful when you want a specific amount of steps instead of a specific step size, so in the case of this example I'd go with the colon notation indeed.
The dot in front of the power and multiplication functions, ^
and *
, makes MATLAB evaluate those element wise, meaning that for all elements in x
the function is evaluated. Omitting those dots would make MATLAB use ^
and *
as matrix operations.
The line:
x=0:0.1:3
Creates a vector from 0 to 3, in jumps of 0.1, as so:
0,0.1,0.2,...,1.9,2.0,...3.0
Where the value of 2.0 is at index 21. So in order to deduce the value of f(2), you actually want to check the output of the function f(x) for the value at index 21, i.e f(21)