define an objective function with user defined number of variables in fminunc()
Suppose I want to define the following function in matlab which returns the output of fminunc(). The problem here is the number of variables depends on the user input. How do I define the objective function fun() such that it automatically adapts to the number of variables.
function xmin = problem(n)
if n == 1
fun = @(x) x^2+2*x+3;
xmin = fminunc(fun,1);
end
if n == 2
fun = @(x) x(1)^2+x(2)^2+2*(x(1)+x(2))+3;
xmin = fminunc(fun,[1 0]);
end
if n == 3
fun = @(x) x(1)^2+x(2)^2+x(3)^2+2*(x(1)+x(2)+x(3))+3;
xmin = fminunc(fun,[1 0 0]);
end
% n is the number of variables for fun.
% the list goes on. n==4, n==5,…
endSuppose I want to define the following function in matlab which returns the output of fminunc(). The problem here is the number of variables depends on the user input. How do I define the objective function fun() such that it automatically adapts to the number of variables.
function xmin = problem(n)
if n == 1
fun = @(x) x^2+2*x+3;
xmin = fminunc(fun,1);
end
if n == 2
fun = @(x) x(1)^2+x(2)^2+2*(x(1)+x(2))+3;
xmin = fminunc(fun,[1 0]);
end
if n == 3
fun = @(x) x(1)^2+x(2)^2+x(3)^2+2*(x(1)+x(2)+x(3))+3;
xmin = fminunc(fun,[1 0 0]);
end
% n is the number of variables for fun.
% the list goes on. n==4, n==5,…
end Suppose I want to define the following function in matlab which returns the output of fminunc(). The problem here is the number of variables depends on the user input. How do I define the objective function fun() such that it automatically adapts to the number of variables.
function xmin = problem(n)
if n == 1
fun = @(x) x^2+2*x+3;
xmin = fminunc(fun,1);
end
if n == 2
fun = @(x) x(1)^2+x(2)^2+2*(x(1)+x(2))+3;
xmin = fminunc(fun,[1 0]);
end
if n == 3
fun = @(x) x(1)^2+x(2)^2+x(3)^2+2*(x(1)+x(2)+x(3))+3;
xmin = fminunc(fun,[1 0 0]);
end
% n is the number of variables for fun.
% the list goes on. n==4, n==5,…
end fminunc MATLAB Answers — New Questions