I'm starting to use functions handles in Matlab and I have a question, what Matlab computes when I do:
y = (0:.1:1)';
fun = @(x) x(1) + x(2).^2 + exp(x(3)*y)
and what Matlab computes when I do:
fun = @(x) x + x.^2 + exp(x*y)
Because I'm evaluating the Jacobian of these functions (from this code ) and it gives different results. I don't understand the difference of putting x(i) or only x
Let's define a vector vec
as vec = [1, 2, 3]
.
When you use this vec
in your first function as results = fun(vec)
, the program will take only the particular elements of the vector, meaning x(1) = vec(1)
, x(2) = vec(2)
and x(3) = vec(3)
. The whole expression then will look as
results = vec(1) + vec(2).^2 + exp(vec(3)*y)
or better
results = 1 + 2^2 + exp(3*y)
However, when you use your second expression as results = fun(vec)
, it will use the entire vector vec
in all the cases like this
results = vec + vec.^2 + exp(vec*y)
or better
results = [1, 2, 3] + [1^2, 2^2, 3^2] + exp([1, 2, 3]*y)
You can also clearly see that in the first case, I don't really need to care about matrix dimensions, and the final dimensions of the results
variable are the same as the dimensions of your y
variable. This is not the case in the second example, because you multiply matrices vec
and y
, which (in this particular example) results in error, as the vec
variable has dimensions 1x3
and the y
variable 11x1
.