How do I fix this issue with fgoalattain?
3 次查看(过去 30 天)
显示 更早的评论
I've formulated the below goal attainment problem:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1197663/image.png)
When I set up the code in MATLAB using fgoalattain, I seem to be getting an issue in regards to the 'x0' variable. What am I doing wrong here?
Code:
clc
clear all
fun = @(x)[x(12)+x(22)+x(32);x(34);x(11)+x(21)+x(31);x(12)+x(22)+x(32);x(13)+x(23)+x(33);x(14)+x(24)+x(34);x(999);x(21)];
goal = [250,80,416,200,320,304,24750,0];
weight = [1,1,1,1,1,1,1,1];
x0=[1];
A = [1,1,1,1,0,0,0,0,0,0,0,0
0,0,0,0,1,1,1,1,0,0,0,0
0,0,0,0,0,0,0,0,1,1,1,1];
b= [420
610
340];
x = fgoalattain(fun,x0,goal,weightA,b)
Output:
Index exceeds the number of array elements. Index must not
exceed 1.
Error in HW12_2>@(x)[x(12)+x(22)+x(32);x(34);x(11)+x(21)+x(31);x(12)+x(22)+x(32);x(13)+x(23)+x(33);x(14)+x(24)+x(34);x(999);x(21)] (line 4)
fun = @(x)[x(12)+x(22)+x(32);x(34);x(11)+x(21)+x(31);x(12)+x(22)+x(32);x(13)+x(23)+x(33);x(14)+x(24)+x(34);x(999);x(21)];
Error in goalcon (line 63)
f = feval(funfcn{3},x,varargin{:});
Error in fgoalattain (line 437)
[ctmp,ceqtmp] = feval(cfun{3},xnew,extravarargin{:});
Error in HW12_2 (line 14)
x = fgoalattain(fun,x0,goal,weight)
Caused by:
Failure in initial objective function evaluation.
Optimization cannot continue.
10 个评论
Walter Roberson
2022-11-18
编辑:Walter Roberson
2022-11-18
Your fundamental mistake is in looking at variable names such as
and deciding that must be represented as x(34) .
is just a variable name and the 34 does not need to be the subscript.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1199158/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1199158/image.png)
Consider this:
fun = @(x5,x11,x12,x13,x14,x21,x22,x24,x23,x31,x32,x33,x34)[x12+x22+x32;x34;x11+x21+x31;x12+x22+x32;x13+x23+x33;x14+x24+x34;x5;x21];
wrapper = @(x) fun(x(1),x(2),x(3),x(4),x(5),x(6),x(7),x(8),x(9),x(10),x(11),x(12),x(13))
Now if you were to fgoalattain asking to optimize function wrapper then you would have been able to use the names that are familiar to you, but at the same time fgoalattain would be working with the vector of values that it is required to work with.
You would have to make sure that your A matrix was built properly. You could do that using names such as
X5=1; X11=2; X12=3; %and so on to X34=13
A(1, [X12, X13, X14, X15]) = 1;
A(2, [X21, X22, X23, X24]) = 1;
%and so on
Or.. you could look into Problem Based Optimization; https://www.mathworks.com/help/optim/problem-based-approach.html
Or... you could use the Symbolic Toolbox the way I showed, in order to construct the problem matrices and the function to be optimized.
回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!