0

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

Mansoor
  • 2,357
  • 1
  • 17
  • 27
JCV
  • 447
  • 1
  • 5
  • 15

2 Answers2

3

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.

Vaclav Pelc
  • 582
  • 6
  • 20
2

If you want to investigate this, I recommend you split this up into subexpressions and debug, e.g.

f1 = @(x) x(1);
f2 = @(x) x(2).^2;
f3 = @(x) exp(x(3)*y);
f  = @(x) f1(x) + f1(x) + f3(x)

You can split it up even further if any subexpression is unclear.

The distinction is that one is an array array multiplication (x * y, I'm assuming x is an array with 11 columns in order for the matrix multiplication to be consistent) and the other is a scalar array multiplication (x(3) * y). The subscript operator (n) for any matrix extracts the n-th value from that matrix. For a scalar, the index can only be 1. For a 1D array, it extracts the n-th element of the column/row vector. For a 2D array, its the n-th element when traversed columnwise.

Also, if you only require the first derivative, I suggest using complex-step differentiation. It provides reduced numerical error and is computationally efficient.

Mansoor
  • 2,357
  • 1
  • 17
  • 27