How can I do Exhaustive search in matlab?

I have a function that depends on three variables x,y,z. I want to find the optimal values of these variables using exhaustive search that can maximize this function, subject to x+y+z<=1. How can I do this in Matlab?

 Accepted Answer

xvalues = [list all possible x values]
yvalues = [list all possible y values]
zvalues = [list all possible z values];
[X, Y, Z] = ndgrid(xvalues, yvalues, zvalues);
mask = X + Y + Z <=1;
x = X(mask);
y = Y(mask);
z = Z(mask);
f = x.^3 - log(y+z) + sin(z); %compute everything. %use appropriate function
[bestf, bestidx] = min(f); %or max(f) depending what you are trying to optimize
bestx = x(bestidx);
besty = y(bestidx);
bestz = z(bestidx);

5 Comments

If I have
for P = 1:1:10;
mask = X + Y + Z <=P; %instead of 1 only
and I want to plot (bestf,P). How can I do this?
Pvals = 1:10;
numP = length(Pvals);
maxP = max(Pvals);
xvalues = [list all possible x values]
yvalues = [list all possible y values]
zvalues = [list all possible z values];
[X, Y, Z] = ndgrid(xvalues, yvalues, zvalues);
mask = X + Y + Z <= maxP;
x = X(mask);
y = Y(mask);
z = Z(mask);
f = x.^3 - log(y+z) + sin(z); %compute everything. %use appropriate function
bestf = zeros(1, numP);
for Pidx = 1 : numP
P = Pvals(Pidx);
mask = x + y + z <= P;
bestf(Pidx) = min(f(mask));
end
plot(Pvals, bestf)
Hello Walter, if I have two more contraints, for example: x <= y and y <= z. How can I add them to your code?
mask = X + Y + Z <= maxP & X <= Y & Y <= Z;
Thanks so much, it works.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!