I want to find the local minimum of the function using loop.
Basically, the function has 2 choice variables say f(x,y).
But I want to find the minimum of f(x,y) with y values starting from 1,2,3...10 using for loop.
For example,
obj = @(x,y) x^2 x*y y^2
for i = 1:30
fminsearch(...)
end
but I am not sure how to use it correctly.
Can anyone help me with this issue?
Thanks in advance.
CodePudding user response:
You can use a wrapper function:
obj = @(x,y) x^2 x*y y^2;
for i = 1:30
y_i = generate_ith_y_value(i);
fminsearch(@(x) obj(x,y_i), x0)
end
If you want to find the pair (x,y)
so that obj(x,y)
is a local minimum rather than finding the local minimum when y is a fixed value (like what you tried to do with for loop), then it's better to combine x
and y
into a single vector.
You can modify obj
directly:
% x(1) = x, x(2) = y
obj = @(x) x(1)^2 x(1)*x(2) x(2)^2;
fminsearch(@(x) obj(x), [x0; y0])
If you can't modify obj
directly, use a wrapper function that takes one input parameter and seperates it:
obj = @(x,y) x^2 x*y y^2;
% xx(1) = x, xx(2) = y
fminsearch(@(xx) obj(xx(1),xx(2)), [x0; y0])