0

I want to get the array of results of a function using as input an array of values. The function receives two variables (x1, x2) and a constant x3, so I'm trying to input all combination of it in a range using mesh.

The result is incorrect, I'm missing something.

Sample:

fun = @(x1,x2,x3) (x2-x1^2)^2+(1-x1)^2 + x3;
x3 = 7;
fun2 = @(x) fun(x(1,1),x(1,2),x3);

x0 = [2 3];
min = fminsearch(fun2, x0);
disp(min);

x = min(1)-10:1:min(1)+10;
y = min(2)-10:1:min(2)+10;

[X,Y] = meshgrid(x,y);

% I'm getting strange values here, like z < 0, how it is possible if everything is squared in the function.
Z = fun(X,Y,x3);
3
  • 1
    My guess: you should be using element-wise operations, e.g. .^ instead of the matrix operations, e.g., ^, when defining fun. Commented Apr 1, 2016 at 16:52
  • LOL, done... Thanks. I think you should write it as an answer. Commented Apr 1, 2016 at 16:57
  • Glad it was helpful. Posted as answer :) Commented Apr 1, 2016 at 17:11

1 Answer 1

1

It's important to note that there is a difference between matrix and element-wise operations in MATLAB.

Matrix operations are defined via plain operators, such as *, or ^. So for example, A*B performs a matrix multiplication between A and B.

Element-wise operators make use of the dot . before the operator, i.e., .*, .^, and so on. Thus, A.*B performs an element-wise multiplication of A and B. The end result of this operation is an array of the same size as A and B (whose sizes must be equal), where the jj'th element of the array is equal to A(jj)*B(jj).

Now, consider your definition of fun:

fun = @(x1,x2,x3) (x2-x1^2)^2+(1-x1)^2 + x3;

What happens when MATLAB evaluates this expression is that it applies the matrix operations, such as ^ to the input arrays. However, to obtain your desired result of applying the operation to every individual element in your input arrays x1, x2, you should be using element-wise operations.

A new definition

fun = @(x1,x2,x3) (x2-x1.^2).^2+(1-x1).^2 + x3;

should provide the desired result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.