How to correct the error in code?

1 view (last 30 days)
clc;
clear all;
a1=3;b1=8;
G=[0;1.5;2;3.5;4;4.5;4.5];
L=[3.0;2.5;3.5;3.5;3.2;4.2;4.0];
H=[40;40;40;20;20;20;20];
k=2;
a1(2)=3;a1(1)=2.5;
b(2)=8 ;b(1)=7.5;
A(:,k)=ones(7,1);
A(:,k-1)=zeros(7,1);
for i=1:1:length(G)
if Egm>0
x = [x i];
elseif Egm<0
y = [y i];
else
z = [z i];
end
end
for j=x(1):1:x(length(x))
A(j,k+1)=((H(j))/(a1(k)))-1 ;
end
F1=@(A)(-H(x,:).*log(1+A(x,:))+a1(k).*(G(x,:)-A(x,:)));
x0=0;
lb1=-100;
ub1=100;
[A,fval]=fmincon(F1,x0,[],[],[],[],lb1,ub1)
While run this program an error shows
Index in position 1 exceeds array bounds.
Index must not exceed 1.
Caused by:
Failure in initial objective function evaluation. FMINCON cannot continue.
Sometimes it shows the error
Error using fmincon (line 641)
Supplied objective function must return a
scalar value.
How to correct this errors?What is the reason for this?
  1 Comment
Rik
Rik on 30 Jan 2023
I recovered the removed content from the Google cache (something which anyone can do). Editing away your question is very rude. Someone spent time reading your question, understanding your issue, figuring out the solution, and writing an answer. Now you repay that kindness by ensuring that the next person with a similar question can't benefit from this answer.

Sign in to comment.

Accepted Answer

Riccardo Scorretti
Riccardo Scorretti on 2 May 2022
Hi Susan,
there is a macroscopic error in your code:
F1=@(A)(-H(x,:).*log(1+A(x,:))+a1(k).*(G(x,:)-A(x,:)));
You defined an inline function F1 which is function of the variable A (which, by the way, is a matrix). I guess you wish to optimize this quantity with respect of x. However, a few lines after you requires A as result of the optimization, but you are passing x0 as starting point for the optimization; this is very confusing.
There is a second problem, which I'm afraid you have to solve by yourself. Assuming that the optimization variable is x, you are using x as index for a matrix. Hence x has to be an integer in the range [1 7] where 7 is the number of rows of A. You are optimizing x as a not necessarily integer value, with bounds [-100 100].
In other words, your program cannot work because the problem that you want to solve is badly formulated. You are the best person to know what you want to solve, so you have to reformulate clearly your own problem. Then we can support you to implement in MATLAB.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!