For each fmincon it overwrites the previous values, meaning at the end there is only 1 set of values when there should be 100. The code is running 100 times and displays all sets of values but not storing all sets. How do I resolve this?

1 次查看(过去 30 天)
for X=1:1:10
for Y=1:1:10
ObjFcn = @myObjective;
x0 = [10 0.001 7];
LB = [0 0 0];
UB = [50 0.5 7.5];
ConsFcn = @(x)myConstraints(x,X,Y);
[x] = fmincon(ObjFcn,x0,[],[],[],[],LB,UB,ConsFcn);
disp(x)
disp(myObjective(x))
end
end

采纳的回答

Alan Weiss
Alan Weiss 2018-4-2
Your code is inefficient in that you define many things inside the loop that should be assigned outside the loop. Using Walter's suggestion, try this:
ObjFcn = @myObjective;
x0 = [10 0.001 7];
LB = [0 0 0];
UB = [50 0.5 7.5];
x = zeros(10,10); % initialization
for X=1:10
for Y=1:10
ConsFcn = @(x)myConstraints(x,X,Y);
x(X,Y) = fmincon(ObjFcn,x0,[],[],[],[],LB,UB,ConsFcn);
disp(x(X,Y))
disp(myObjective(x(X,Y)))
end
end
  5 个评论
Walter Roberson
Walter Roberson 2018-4-2
ObjFcn = @myObjective;
x0 = [10 0.001 7];
LB = [0 0 0];
UB = [50 0.5 7.5];
x = zeros(10,10,3 ); % initialization
fvals = inf(10,10); % initialization
for X=1:10
for Y=1:10
ConsFcn = @(x)myConstraints(x,X,Y);
[x(X,Y,:), fvals(X,Y)] = fmincon(ObjFcn,x0,[],[],[],[],LB,UB,ConsFcn);
disp(x(X,Y))
disp(myObjective(x(X,Y)))
end
end
Scott Sanders
Scott Sanders 2018-4-3
That seems to have done the trick. The final code that works is:
ObjFcn = @myObjective;
x0 = [10 0.001 7];
LB = [0 0 0];
UB = [100 0.3 7.5];
x=zeros(10,10,3);
fvals=inf(10,10);
for X=1:10
for Y=1:10
ConsFcn = @(x)myConstraints(x,X,Y);
[x(X,Y,:),fvals(X,Y)] = fmincon(ObjFcn,x0,[],[],[],[],LB,UB,ConsFcn);
disp(x(X,Y,:))
disp(myObjective(x(X,Y,:)))
end
end
Thank you all for your help!

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2018-4-2
Instead of assigning to x assign to x(X, Y)

类别

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