Clear Filters
Clear Filters

Error in prob.Objective

4 views (last 30 days)
Angga Fernando
Angga Fernando on 24 Aug 2021
Dear All,
I tried to solve optimization problem with objective to minimize the result (cost), the code is below :
% Source Data
InvCost = [700 600 650 800 400]';
Cap = [750 750 750 750 750]';
DelCost = [3 0 5 6 8 5 5; 4 4 5 5 7 0 3; 5 7 3 5 7 4 0; 5 6 0 6 7 3 2; 6 6 6 0 2 5 6];
Demand = [500 400 150 350 300 400 200];
% Create Objective
prob = optimproblem('ObjectiveSense','minimize');
X1 = optimvar('X1',5,1,'Type','integer','LowerBound',0,'UpperBound',1);
X2 = optimvar('X2',5,7,'Type','integer','LowerBound',0,'UpperBound',[]);
cost = (InvCost'*X1)+(DelCost'*X2);
prob.Objective = cost;
% Create Constraints - Demand
ConsDemand = sum(X2)==Demand;
prob.Constraints.ConsDemand = ConsDemand;
% Create Constraints - Capacity
ConsCap = sum(X2)-(Cap'*X1);
prob.Constraints.ConsCap = ConsCap;
% Create Solution
[sol,fval] = solve(prob);
When tried to run the code, I got error message on "prob.Objective = cost " that
"Objective must be a scalar OptimizationExpression or a struct containing a scalar OptimizationExpression."
Attached pic below :
Anyone here can help me, how to solve this issue ? Is the code I have written correct or not?
Thank you for your kindly help.

Answers (1)

prabhat kumar sharma
prabhat kumar sharma on 2 May 2024
Hi Angga,
I understand that you are facing this error in your objective function.
I tried to analyze your objective function, that is defined as:
cost = (InvCost'*X1) + (DelCost'*X2);
Here, InvCost is a column vector (5x1), and X1 is a matrix (5x1) of optimization variables. Their product, InvCost'*X1, is a scalar, which is correct.
However, DelCost is a matrix (5x7), and X2 is also a matrix (5x7) of optimization variables. Their product, DelCost'*X2, will result in a matrix (5x7), not a scalar, which is the source of the error.
To correct the error, you need to ensure that the entire expression for cost results in a scalar. For the delivery cost part, you want to sum all elements of the product of DelCost and X2 to get a total delivery cost. This can be achieved by element-wise multiplication followed by summing all elements.
Here's how you can correct it:
% Corrected Objective Function
cost = sum(InvCost'*X1) + sum(sum(DelCost.*X2));
I hope it helps to resolve your error!

Categories

Find more on Get Started with Optimization Toolbox in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!