MATLAB Answers

someone please help me. I have made a 2 variable code for optimization, I want code for "n" no. of variables.

32 views (last 30 days)
SAKSHAM SHRIVASTAVA on 13 Apr 2021 at 15:53
Answered: Alan Weiss on 13 Apr 2021 at 19:54
format long
% Function Definition (Enter your Function here):
syms X Y;
f = -X - Y + 0.5*X^2 + X*Y + Y^2;
% Initial Guess:
x(1) = 0;
y(1) = 0;
e = 10^(-8); % Convergence Criteria
i = 1; % Iteration Counter
% Gradient Computation:
df_dx = diff(f, X);
df_dy = diff(f, Y);
J = [subs(df_dx,[X,Y], [x(1),y(1)]) subs(df_dy, [X,Y], [x(1),y(1)])]; % Gradient
S = -(J); % Search Direction
% Minimization Condition:
while norm(S) > e
I = [x(i),y(i)]';
syms h; % Step size
g = subs(f, [X,Y], [x(i)+S(1)*h,y(i)+h*S(2)]);
dg_dh = diff(g,h);
h = solve(dg_dh, h); % Optimal Step Length
x(i+1) = I(1)+h*S(1); % New x value
y(i+1) = I(2)+h*S(2); % New y value
J_old = [subs(df_dx,[X,Y], [x(i),y(i)]) subs(df_dy, [X,Y], [x(i),y(i)])];
i = i+1;
J_new = [subs(df_dx,[X,Y], [x(i),y(i)]) subs(df_dy, [X,Y], [x(i),y(i)])]; % Updated Gradient
S = -(J_new)+((norm(J_new))^2/(norm(J_old))^2)*S; % New Search Direction
% Result Table:`
Iter = 1:i;
X_coordinate = x';
Y_coordinate = y';
Iterations = Iter';
T = table(Iterations,X_coordinate,Y_coordinate);
% Plots:
fcontour(f, 'Fill', 'On');
hold on;
% Output:
fprintf('Initial Objective Function Value: %d\n\n',subs(f,[X,Y], [x(1),y(1)]));
if (norm(S) < e)
fprintf('Minimum succesfully obtained...\n\n');
fprintf('Number of Iterations for Convergence: %d\n\n', i);
fprintf('Point of Minima: [%d,%d]\n\n', x(i), y(i));
fprintf('Objective Function Minimum Value: %d\n\n', subs(f,[X,Y], [x(i),y(i)]));

Answers (1)

Alan Weiss
Alan Weiss on 13 Apr 2021 at 19:54
It is probably a bit easier to write code for NUMERIC minimizaton of an arbitrary-sized expression than a hybrid SYMBOLIC minimization. But feel free to do what you want.
You need to write code that can take an arbitrary N as the number of dimensions. For example,
% Assume N exists
X = sym('X',[N,1]);
% Write code that uses N-dimensional vector X
% Assume fun is defined in terms of X, fun is a scalar expressioon
G = gradient(fun,X); % Calculates the gradient, no loop needed
while(norm(G) > 1e-8)
step = gradient(fun,X);
X = X - fun(X)*step; % or whatever algorithm you like
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation

Community Treasure Hunt

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

Start Hunting!