Skip to content

Commit 3a713e7

Browse files
Paul Kerr-Delworthccreutzi
authored andcommitted
Add Build Optimization Problem example
Add Optimization and Global Optimization Toolboxes as products used in the example. Add a link to the example in README.md Add Optimization and Global Optimization Toolboxes as required products to run the tests.
1 parent 8bdb725 commit 3a713e7

19 files changed

Lines changed: 431 additions & 0 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ jobs:
4040
products: >
4141
Text_Analytics_Toolbox
4242
Curve_Fitting_Toolbox
43+
Optimization_Toolbox
44+
Global_Optimization_Toolbox
4345
cache: true
4446
- name: Run tests and generate artifacts
4547
env:

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ For more information about how to connect to the different APIs from MATLAB, inc
6262
- [Fit Polynomial to Data Using AI Agent](/examples/FitPolynomialToDataUsingAIAgentExample.md) (requires Curve Fitting Toolbox™)
6363
- [Analyze Table Data Using ChatGPT](/examples/AnalyzeTableDataUsingChatGPTExample.md)
6464
- [Visualize Table Data Using ChatGPT](/examples/VisualizeTableDataUsingChatGPTExample.md)
65+
- [Build Optimization Problem Using ChatGPT](/examples/BuildOptimizationProblemUsingChatGPTExample.md) (requires Optimization Toolbox™ and Global Optimization Toolbox™)
6566
### Tool Calling
6667
- [Analyze Scientific Papers Using ChatGPT Function Calls](/examples/AnalyzeScientificPapersUsingFunctionCalls.md)
6768
- [Analyze Text Data Using Parallel Function Calls with ChatGPT](/examples/AnalyzeTextDataUsingParallelFunctionCallwithChatGPT.md)
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
# Solve Optimization Problem Using ChatGPT
2+
3+
This example shows how to solve optimization problems in MATLAB® using ChatGPT™.
4+
5+
- Build a prompt that describes an optimization problem to ChatGPT
6+
- Generate code to solve the problem using ChatGPT
7+
- Solve the problem and verify the solution
8+
9+
This example uses the Optimization Toolbox™ and Global Optimization Toolbox™.
10+
11+
# Setup
12+
13+
Using the OpenAI® API requires an OpenAI API key. For information on how to obtain an OpenAI API key, as well as pricing, terms and conditions of use, and information about available models, see the OpenAI documentation at [https://platform.openai.com/docs/overview](https://platform.openai.com/docs/overview).
14+
15+
To connect to the OpenAI API from MATLAB using LLMs with MATLAB, specify the OpenAI API key as an environment variable and save it to a file called ".env".
16+
17+
![image_0.png](./BuildOptimizationProblemUsingChatGPTExample_media/image_0.png)
18+
19+
To connect to OpenAI, the ".env" file must be on the search path.
20+
21+
Load the environment file using the `loadenv` function.
22+
23+
```matlab
24+
loadenv(".env")
25+
```
26+
27+
# Describe Optimization Problem
28+
29+
The optimization problem in this example is a slightly modified version of the spring design problem in the following reference:
30+
31+
*Optimizing engineering designs using a combined genetic search, Deb, K., Goyal, M. Proceedings of the Seventh International Conference on Genetic Algorithms, 521\-528 (1997)*
32+
33+
This example involves the design of a helical compression spring.
34+
35+
![image_1.png](./BuildOptimizationProblemUsingChatGPTExample_media/image_1.png)
36+
37+
Provide the LLM with three pieces of background information on compression springs.
38+
39+
**Total number of coils:** This is equal to two plus the number of active coils, because the two end coils are used for stability, not compression. For more information, see the following reference:
40+
41+
[How to Count Spring Coils: Counting Active & Inactive Coils, Century Spring](https://www.centuryspring.com/resources/how-to-count-spring-coils?srsltid=AfmBOoos9siv9IVL_rNaMYZ29QnWgF6miGPhYKuFlDNsVqcX16zx0JrH)
42+
43+
**Spring index definition**: The ratio of coil diameter to wire diameter. Coils with higher spring indices are more flexible and tolerate lower loads. Also, it’s very difficult to manufacture springs with low spring indices.
44+
45+
**The compression spring is to act linearly under load:** The *"Difference between spring deflection at maximum load and at applied load must be at least 1.25in."* constraint below ensures that the spring deflection is linearly dependent on the applied load.
46+
47+
Describe the optimization problem in natural language.
48+
49+
```matlab
50+
problemDescription = ...
51+
"You want to design a helical compression spring." + newline + ...
52+
"The coil volume should be as small as possible." + newline + ...
53+
"You can decide on the number of coils in the spring, the diameter of the coil, and the wire diameter." + newline + ...
54+
"The spring can have no more than 32 coils." + newline + ...
55+
"You will apply a 300 lb load to the spring." + newline + ...
56+
"The spring can be no longer than 14 in." + newline + ...
57+
"The wire diameter must be no smaller than 0.2 in and no larger than 0.5 in." + newline + ...
58+
"The coil diameter must be no larger than 3 in." + newline + ...
59+
"The total diameter must be no bigger than 3 in." + newline + ...
60+
"The spring must not deflect more than 6 in." + newline + ...
61+
"The spring index must be at least 3." + newline + ...
62+
"Difference between spring deflection at maximum load and at applied load must be at least 1.25 in." + newline + ...
63+
"The shear stress must not exceed 0.12 Mpsi at the applied load." + newline + ...
64+
"The maximum shear stress of the material must not be exceeded at maximum load." + newline + ...
65+
"The coil volume must not exceed 30 in^3" + newline + ...
66+
"The modulus of rigidity is 11.5e6 psi." + newline + ...
67+
"The maximum shear stress of the material is 0.189e6 psi." + newline + ...
68+
"The maximum load of the material is 1000 lb.";
69+
```
70+
71+
The coil constants are for ASTM A228 material.
72+
73+
# Specify Spring Functions
74+
75+
The `CoilSpringFunctions` folder contains several functions that calculate spring characteristics based on the coil constants and configuration. Add the folder to the path.
76+
77+
```matlab
78+
projectDir = fileparts(which("openAIChat"));
79+
functionFolderDir = fullfile(projectDir,"examples","mlx-scripts","CoilSpringFunctions");
80+
addpath(functionFolderDir);
81+
```
82+
83+
Now run a function to gather information about the functions. This will allow ChatGPT to generate code that correctly calls the functions. This helper function is defined in the **Supporting Functions** section at the bottom of this example.
84+
85+
```matlab
86+
[functionFirstLines, functionInputStruct] = collectFunctionInfo(functionFolderDir);
87+
```
88+
89+
This function also returns a structure where you can provide information on the input sizes. This sizes are all initialized to scalars, which matches the input sizes in this example. You can edit the structure manually for any future examples.
90+
91+
# Initialize ChatGPT
92+
93+
Read a system prompt into ChatGPT that includes advice on how to build OptimizationProblems in MATLAB.
94+
95+
```matlab
96+
systemPromptFile = fullfile(functionFolderDir, "systemPrompt.md");
97+
systemPrompt = strjoin(strip(readlines(systemPromptFile)), newline);
98+
```
99+
100+
Create an LLM model that will help build the Optimization Problem in MATLAB.
101+
102+
```matlab
103+
mdl = openAIChat(systemPrompt,ModelName="gpt-5.2");
104+
```
105+
106+
# Ask ChatGPT to generate code to solve your Optimization Problem
107+
108+
Create a prompt from the problem description plus the function and data information.
109+
110+
```matlab
111+
functionInputSizesString = string(jsonencode(functionInputStruct));
112+
prompt = ...
113+
"The following functions are on the MATLAB path:" + newline + ...
114+
functionFirstLines + newline + newline + ...
115+
"The function inputs have the following sizes:" + newline + ...
116+
functionInputSizesString + newline + newline + ...
117+
"Formulate the following problem in MATLAB. Use the variable name coilProblem for the OptimizationProblem." + newline + ...
118+
problemDescription;
119+
```
120+
121+
Now, ask ChatGPT to create code to solve the optimization problem
122+
123+
```matlab
124+
problemCode = generate(mdl, prompt);
125+
```
126+
127+
# Solve your Optimization Problem
128+
129+
To solve optimization problems in MATLAB, the [problem\-based workflow](https://www.mathworks.com/help/optim/ug/problem-based-workflow.html) is the recommended approach. The LLM has been instructed to produce problem\-based workflow code to solve the coil problem. Validate the code by reviewing it in a dialog, then run the code to solve the coil problem.
130+
131+
```matlab
132+
[sol, fval, exitflag] = runGeneratedCodeWithApproval(problemCode)
133+
```
134+
135+
```matlabTextOutput
136+
Solving problem using ga.
137+
ga stopped because the average change in the penalty function value is less than options.FunctionTolerance and
138+
the constraint violation is less than options.ConstraintTolerance.
139+
sol = struct with fields:
140+
coilDiameter: 1.4981
141+
numCoils: 6
142+
wireDiameter: 0.2978
143+
144+
145+
fval = 2.6224
146+
exitflag =
147+
SolverConvergedSuccessfully
148+
149+
150+
```
151+
152+
# Verify the result
153+
154+
The `ga` function from the Global Optimization Toolbox was chosen automatically to solve the problem and it converged successfully to a solution. The best design returned from `solve` has the following properties:
155+
156+
- Number of coils (N): $6$
157+
- Wire diameter (d): $0\ldotp 298\mathrm{in}$
158+
- Coil diameter (D): $1\ldotp 498\mathrm{in}$
159+
- Coil volume: ${2\ldotp 622\mathrm{in}}^3$
160+
161+
The best coil volume returned is slightly lower than that reported in Deb & Goyal. This is due to the fact the problem in this example has a continuous wire diameter rather than the discrete values in Deb & Goyal.
162+
163+
The output of LLMs is not guaranteed to be accurate. It is important to verify the solution to ensure it satisfies the requirements specified in the problem description. To illustrate this, check the deflection requirement by evaluating `coilDeflection` at the solution
164+
165+
*The spring must not deflect more than 6 in.*
166+
167+
```matlab
168+
maxLoad = 1000;
169+
modulusOfRigidity = 11.5e6;
170+
coilDeflection(sol.numCoils, sol.wireDiameter, sol.coilDiameter, maxLoad, modulusOfRigidity)
171+
```
172+
173+
```matlabTextOutput
174+
ans = 1.7845
175+
```
176+
177+
The coil deflection (1.7845`in`) meets the requirement at the solution.
178+
179+
# Supporting Functions
180+
181+
## Describe Function Syntax
182+
183+
Define a local function named `collectFunctionInfo` that returns the API of any MATLAB functions and a structure containing function input sizes. The function accepts the directory containing the functions as input.
184+
185+
```matlab
186+
function [funInfo, inputSizeStruct] = collectFunctionInfo(functionDir)
187+
188+
189+
% Find all MATLAB functions in problem directory
190+
MATLABFunctions = dir(fullfile(functionDir, "*.m"));
191+
numFiles = numel(MATLABFunctions);
192+
funStrings = strings(1, numFiles);
193+
funInputs = cell(1, numFiles);
194+
for i = 1:numFiles
195+
thisFile = readlines(fullfile(MATLABFunctions(i).folder, MATLABFunctions(i).name));
196+
funStrings(i) = extractAfter(thisFile(1), "function ");
197+
funInputs{i} = extractBetween(funStrings(i), "(", ")");
198+
funInputs{i} = strip(strsplit(funInputs{i}, ","));
199+
end
200+
funInfo = join(funStrings, newline);
201+
202+
203+
% Next, build the input size substructure
204+
funInputs = unique([funInputs{:}]);
205+
for i = 1:numel(funInputs)
206+
inputSizeStruct.(funInputs{i}) = [1 1];
207+
end
208+
end
209+
```
210+
211+
## Request Approval and Evaluate LLM\-Generated Code
212+
213+
Create a dialog that displays the code to create an `OptimizationProblem` that ChatGPT generated and requests user approval to run the code. If approved, evaluate the code.
214+
215+
This function accepts the generated code, and the constants that will be used when the code is evaluated.
216+
217+
```matlab
218+
function [sol, fval, exitflag] = runGeneratedCodeWithApproval(code, modulusOfRigidity, maxShearStress, maxLoad)
219+
code = extractBetween(code, "```matlab", "```");
220+
figurename = "Review Code Generated by LLM";
221+
fig = uifigure(WindowStyle="modal",Name=figurename,UserData=struct("Approved",false));
222+
fig.Position([3 4]) = [1000 750];
223+
movegui(fig,"center")
224+
gridLayout = uigridlayout(fig,RowHeight=["fit" "1x" "fit" "fit"],ColumnWidth=["1x" "fit" "fit"]);
225+
label1 = uilabel(gridLayout,Text="The third-party LLM you selected generated the following code:");
226+
label1.Layout.Row = 1;
227+
label1.Layout.Column = [1 3];
228+
codeBox = uitextarea(gridLayout,Value=code,WordWrap="off",Editable="off",FontName="Monospaced");
229+
codeBox.Layout.Row = 2;
230+
codeBox.Layout.Column = [1 3];
231+
label2 = uilabel(gridLayout,Text="MATLAB cannot guarantee the accuracy or security " + ...
232+
"of code generated from a third-party AI model.",FontAngle="italic");
233+
label2.Layout.Row = 3;
234+
label2.Layout.Column = [1 3];
235+
uilabel(gridLayout,Text="Do you want to run this code in MATLAB?",FontWeight="bold");
236+
uibutton(gridLayout,Text="Run Code",ButtonPushedFcn=@(btn,evt) setApproved(fig,true));
237+
uibutton(gridLayout,Text="Cancel",ButtonPushedFcn=@(btn,evt) setApproved(fig,false));
238+
uiwait(fig);
239+
approved = fig.UserData.Approved;
240+
delete(fig);
241+
if approved
242+
eval(code)
243+
else
244+
error("Running the generated code was canceled.")
245+
end
246+
end
247+
```
248+
249+
Record whether the user approved or did not approve running the generated code.
250+
251+
```matlab
252+
function setApproved(fig,approvalStatus)
253+
fig.UserData.Approved = approvalStatus;
254+
uiresume(fig);
255+
end
256+
```
257+
258+
# Using AI Agents
259+
260+
This example use a one shot call to ChatGPT to generate MATLAB code. If your workflow is too complicated for this approach, then you can build and use an AI agent. For an example of building an AI agent, see [Solve Simple Math Problem Using AI Agent](https://github.com/matlab-deep-learning/llms-with-matlab/blob/main/examples/SolveSimpleMathProblemUsingAIAgent.md).
261+
262+
*Copyright 2026 The MathWorks, Inc.*
Binary file not shown.
6.05 KB
Loading
192 KB
Loading
Binary file not shown.
6.05 KB
Loading
80.4 KB
Loading
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function delta = coilDeflection(numCoils, wireDiameter, coilDiameter, load, modulusOfRigidity)
2+
%COILDEFLECTION Calculate coil deflection
3+
%
4+
% DELTA = COILDEFLECTION(NUMCOILS, WIREDIAMETER, COILDIAMETER, LOAD,
5+
% MODULUSOFRIGIDITY) calculates the deflection of the specified coil
6+
% under the applied LOAD.
7+
8+
% Copyright 2026 The MathWorks, Inc.
9+
10+
arguments (Input)
11+
numCoils (1, 1) double
12+
wireDiameter (1, 1) double
13+
coilDiameter (1, 1) double
14+
load (1, 1) double
15+
modulusOfRigidity (1, 1) double
16+
end
17+
18+
arguments (Output)
19+
delta (1, 1) double
20+
end
21+
22+
delta = load/coilStiffness(numCoils, wireDiameter, coilDiameter, modulusOfRigidity);
23+
24+
end

0 commit comments

Comments
 (0)