I am attempting to implement the fminunc (unconstrained Problem) function in MATLAB. I am getting an error with my code.

2 views (last 30 days)
Objective Function
function r = objfn(x)
x1 = x(1); x2 = x(2); %two design variables
n = size(x1);
for i = 1:n
r(i) = exp((-1.767767*(x1 - x1(i)).^2)+(-1.0511218*(x2-x2(i)).^2));
% this is my equation, where r is a vector matrix of order 25X1
end
a = r'
y = -0.0293 + (a*(G1)); %G1 is a matrix of order
fminunc
% bounds
Lb = [6; 12]; Ub = [8; 15];
x0 = [6.1; 13]; % initial value
x = fminunc(fun,x0)
when i execute i get this error
" Attempted to access x1(2); index is out of bounds because numel(x1) = 1"
I think i have an error in my loop, please help me to rectify it and get the solution, i am new to coding

Answers (1)

Alan Weiss
Alan Weiss on 17 Aug 2015
Your code does not make much sense to me for the following reasons:
  • x1 and x2 are scalars. So what do you expect n to be?
  • Since x1 is a scalar, there is no x1(2), and that is the error you get. What did you want x1(2) to be?
  • Did you pass the matrix G1 to your objective function somehow, or is there a nested function that we cannot see?
I suggest that you put a breakpoint in your code and use the debugger.
Alan Weiss
MATLAB mathematical toolbox documentation

Categories

Find more on Problem-Based Optimization Setup in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!