MATLAB Answers

Evaluate function over a mesh grid (without for loops)

조회 수: 23(최근 30일)
Bill Tubbs
Bill Tubbs 22 Oct 2020
댓글: Rik 22 Oct 2020
Is there a way to evaluate a function that takes an [x, y] vector as input over a grid of points?
Here is the function I want to evaluate:
Jfun = @(u) (17*u(1)^2)/2 - 14*u(1)*u(2) - 40*u(1) + 19*u(2)^2 - 20*u(2)
The reason I defined the function this way is so that I can find the minimum thus:
umin = fminsearch(Jfun,[0,0])
Now I want to make the contour plot.
Something like this perhaps:
x = linspace(-1,6);
y = linspace(-3,5);
[X,Y] = meshgrid(x,y);
for i=1:numel(x)
for j=1:numel(y)
Z(i,j)=Jfun([X(j,i) Y(j,i)]);
end
end
contourf(X,Y,Z,10)
But is there a way to compute Z without having to use nested for loops?
I tried this:
Z = Jfun(cat(3,X,Y));
but it doesn't work. It simply returns 173.5000 which is Jfun([-1 -1]).

  댓글 수: 0

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 22 Oct 2020
You have to vectorize the function and split it into two steps:
Jfun = @(x,y) (17*x.^2)/2 - 14*x.*y - 40*x + 19*y.^2 - 20*y;
umin = fminsearch(@(u) Jfun(u(1),u(2)),[0,0])
x = linspace(-1,6);
y = linspace(-3,5);
[X,Y]=ndgrid(x,y);
Z=Jfun(X,Y);

  댓글 수: 3

Bill Tubbs
Bill Tubbs 22 Oct 2020
Thanks, this works.
Bill Tubbs
Bill Tubbs 22 Oct 2020
Unfortunately the execution of the fminsearch is about 40% slower with this approach but the computation of Z is very fast.
Rik
Rik 22 Oct 2020
You can remove the overhead of the outer layer of anonymous function if that 40% is important for you. That does mean you will have two copies of virtually the same function, but that is a small price to pay.

댓글을 달려면 로그인하십시오.

추가 답변(1개)

madhan ravi
madhan ravi 22 Oct 2020
v = num2cell([X(:), Y(:)], 2);
Z = reshape(cellfun(Jfun, v), size(X));

  댓글 수: 1

Bill Tubbs
Bill Tubbs 22 Oct 2020
Thanks. This works but is not very efficient according to timeit().

댓글을 달려면 로그인하십시오.

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by