How to correct the error in code?

조회 수: 2 (최근 30일)
ANCY S GEORGE
ANCY S GEORGE 2022년 5월 2일
댓글: Rik 2023년 1월 30일
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
Rik
Rik 2023년 1월 30일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Riccardo Scorretti
Riccardo Scorretti 2022년 5월 2일
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.
  댓글 수: 2
ANCY S GEORGE
ANCY S GEORGE 2022년 5월 5일
Ok sir.Thank you
Riccardo Scorretti
Riccardo Scorretti 2022년 5월 6일
You are welcome.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by