# Optimization problem using external program

11 views (last 30 days)
Mario Malic on 10 Oct 2019
Edited: Mario Malic on 11 Oct 2019
Hello everyone,
I am currently dealing with an optimization problem in which I have an objective function to minimize and its result (number) is obtained from a simulation program.
Current progress is that I wrote a script that will automatically feed ("some") numbers in to variables needed to run simulation and obtain the result. After calling an optimization algorithm, it starts doing its own thing, generates variables in each step and calculating the objective function (in which I would like to put results from simulation with generated variables from corresponding step).
What I'm interested in is:
• Is it possible for an algorithm to generate variables for one step only (exit the optimization algorithm), that I will put in the simulation program and calculate objective function, and put this in the loop.
• Should this be done by OutputFunction?
• If there is a better way to do it, I'd love to hear
I hope I wrote it clear enough for you to understand.
Best regards,
Mario

Fabio Freschi on 10 Oct 2019
I can figure out two solutions
1) check if the simulation program has API for running it from "outside". In this case, make reference to the program API documentation
2) if you can run the symulation program from command line and it accepts files as input/output: in your matlab objective function, write a text file with the degrees of freedome values selected by the Matlab optimization algorithm you are using, then run the simulation program and let it read the input file, run the simulaiton, write another text file with the output and read the output from the matlab objective function.
function f = myObjFunction(x)
% write file
fid = fopen('input.txt');
fprintf(...); % <- print your x values
fclose(fid)
command = '...' % <- specify your command, including writing the output
status = system(command);
fid = fopen('output.txt');
fscanf(); % <- read the output
fclose(fid);
end
Reading and writing text files can take a lot, but if the complexity is dominated by the simulation, this method could worth a try
Mario Malic on 10 Oct 2019
Edited: Mario Malic on 11 Oct 2019
1) Unfortunately, it doesn't have
2) I was hoping not to readjust the code for postprocessing the data
I'll update this thread in couple of days.
Thank you Fabio
EDIT:
Calling simulation and postprocessing the results within the objective function solved the issue as stated above.

### Categories

Find more on Direct Search in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!