Alex P.
Alex P.

Reputation: 3787

Convert meshgrid to vector for 2-value function

I have a function like

f = @(x) x(1).^2 + x(2);

I want to draw its plot via surf, so I used meshgrid to generate input data:

[x, y] = meshgrid(-2:.2:2);

But if I try to pass it to the function like this

z = f([x; y])

I get just a single value in result.

Is there any way to do it except making a function that accepts two parameters (x, y) instead of a vector?

Upvotes: 0

Views: 2132

Answers (2)

Douglas Stewart
Douglas Stewart

Reputation: 11

clear
f = @(x) (x(:,:,1) - 1).^2 + 5 * (x(:,:,2) - 1).^2;
[x, y] = meshgrid(-2:.05:2); 
q(:,:,1)=x;
q(:,:,2)=y;
z = f(q);
surf(x,y,z)

Upvotes: 0

Dan
Dan

Reputation: 45752

I think that you really do wany to make f take 2 parameters and I can't think of a good reason not to do it that way but this might be what you're after:

f = @(x) x(:,1).^2 + x(:,2)

Then you might need to call

z = f([x(:),y(:)])

After which you will probably need to call reshape on z so maybe reshape(z,size(x))

But I really think a 2 parameter function is a better way to go:

f2 = @(x1,x2)x1.^2 + x2

and now you can just go

z = f2(x,y)

Another way to go might be to use a wrapper function so if

f = @(x1,x2)x1.^2 + x2

but you really need a function that takes only one parameter then what about

f_wrapper = @(x) f(x{1},x{2}) %// using a cell array

or if you don't want to use a cell array then you could use a struct or a 3D array

f_wrapper = @(x) f(x.x1,x.x2) %// using structs
f_wrapper = @(x) f(x(:,:,1),x(:,:,2)) %// using a 3D matrix

Now you can use f_wrapper in something like fmincon after you package your x and y into a single variable so either a cell array, a struct or a 3D matrix. So for example if you are using the cell-array version above then try

inputVariable = {x,y}

So writing out the example in full

[x, y] = meshgrid(-2:.2:2);
f = @(x1,x2)x1.^2 + x2;
f_wrapper = @(x) f(x{1},x{2});
inputVar = {x,y};
z = f_wrapper(inputVar)

Upvotes: 2

Related Questions