Home > OS >  How can I use fcontour using f(x(1),x(2))?
How can I use fcontour using f(x(1),x(2))?

Time:09-09

I need to use fcontour defining the function with x(1) and x(2), can I do this? or some other solution for plot contour line with the function like

fun1 = @(x) x(1).^2 - 3.*x(1).*x(2)   4.*x(2).^2   x(1) - x(2);

CodePudding user response:

You want f = @(x,y), where z = f(x,y) is the function and x, y are the independent variables and are just symbols. If you want a value of the function at x(1) and x(2), then define x, say x = [1 2];, and call the function like f(x(1),x(2)).

f = @(x,y) x^2 - 3*x*y   4*y^2   x - y;
fcontour(f)

which would show the following plot.

enter image description here

CodePudding user response:

You assert that f should be a function of a single 2-element input, rather than two single-element inputs. But fcontour requires 2 distinct inputs. You can use a helper function to achieve a compromise

fun1 = @(x) x(1).^2 - 3.*x(1).*x(2)   4.*x(2).^2   x(1) - x(2);
fun2 = @(x,y) fun1([x,y]); % helper function to map 2 inputs to a single 2-element array

fcontour( fun2 );

Note that your function construction causes this warning:

Warning: Function behaves unexpectedly on array inputs. To improve performance, properly vectorize your function to return an output with the same size and shape as the input arguments.

The vectorised version to address this would be something like this, although it works regardless

fun1 = @(x) x(:,1).^2 - 3.*x(:,1).*x(:,2)   4.*x(:,2).^2   x(:,1) - x(:,2);
fun2 = @(x,y) reshape(fun1([x(:),y(:)]),size(x)); 

fcontour( fun2 );
  • Related