Can Matlab optimize an external process? [closed] - matlab

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm considering buying Matlab Home + Optimization module for home use, however I'm not sure it can do what I want it to.
I have an external process (not Matlab) that takes input, runs a process, and produces output. I want to tie in the input and output to Matlab so that Matlab can "optimize" these inputs, completely blind to the discrete process itself. Does Matlab have discrete optimization capabilities, or do all of its optimization functions rely on having internal access to the process itself?
Thanks!
-Stephen

if your external process is capable to assimilate parameters and give response to a external program using any methods eg, command line, or files, yes it is possible just configure your objective function to send and read the parameters and response data to the external process.
For the discrete optimization, the optimization toolbox do not work with discrete optimizations problems, but the documentation give a hint about rounding the parameter inside the objective function and then running again in the responses variable.
for example, this can be a function to optimize a volume of a prism
which is coded in a external program written in python (just for demonstration purpose with single objetive genetic algorithm (ga)):
function f = optim(x)
%Optimization criteria
l = round(x(1));
h = round(x(2));
w = round(x(3));
%String to produce the external proccess call as a system command
commandStr = ['python -c "print ' num2str(l) ' * ' num2str(h) ' * ' num2str(w) ' "'];
%Execute the system command, status = 0 for good execution
[status, commandOut] = system(commandStr);
%Convert the output of the external program from strin to doble and assign as the response of the optimization funcition
f = str2double(commandOut)
Then you can use the optimtool using this funcion as objetive as:
Then export the result to workspace and round() it.
Or make it programmable with a code like this:
function [x,fval] = runOptimization(lb,ub)
options = gaoptimset;
options = gaoptimset(options,'Display', 'off');
[x,fval] =ga(#optim,3,[],[],[],[],lb,ub,[],[],options);
x = round(x)
fval = optim(x)
And run as
[x,fval] = runOptimization([1 1 1],[3 4 5])
NOTE. the round() functions its only to demonstrate how to do discrete optimization as suggested in the documentation

Related

Changing function variable to another variable MATLAB [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
Is there a way to change a function variable to another variable?
for instance, if I have the function:
f = #(s) exp(2-s)
I need to change it to
f = #(t) exp(2-t)
without changing it manually.
With the usual caveats that this is a terrible idea :) let's get a little nuts.
First, we can make the anonymous function f
f = #(s) exp(2-s)
For some sample uses, for sanity
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, save it to a file, using the -v7.3 flag to force an H5 file type
save('tempfile','f','-v7.3')
Matlab can read this file as data. After some exploring, we can see that the function is stored, as an evaluation-ready string, here:
char(h5read('tempfile.mat','/f/function_handle/function'))
% Returns 'sf%0#(s)exp(2-s)'
So, it's easy enough to change, using Matlab's H5 write functions
h5write('tempfile.mat','/f/function_handle/function',uint16('sf%0#(x)exp(2-x)'))
Let's see, did it work?
clear f
load('tempfile.mat')
Now we have the following
f =
function_handle with value:
#(x)exp(2-x)
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, we can see a lot of this data without the file saving business, using the functions function. (So meta)
>> f = #(s) exp(2-s);
>> functions(f)
ans =
struct with fields:
function: '#(s)exp(2-s)'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'
This lets you see how Matlab is storing the anonymous function. When debugging, this allows you to see what baggage (stored workspaces and stuff) is associated with the function handle.
However, changes to this structure do not change the actual function handle. I don't know of a way to generate a new function handle from this structure.
Wrap up
[note #1 deleted]
Please, don't ever do this.

why do i get fminsearch undefined function error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to optimize a function with 2 inputs. Trying to use fminsearch but it keeps saying undefined function or variable although it is already defined.
I have already defined the function in a separate script that is in the same directory with my main script. I have a classroom license which includes optimization toolbox and there is no spelling mistake while calling the function.
function o=u(x,y)
%some code here
end
%in a second script
init=[0.1,0.1];
b=fminsearch(o,init);
The error is:
Undefined function or variable 'o'.
From the documentation on fminsearch, the function being minimized must have a single argument and accessed with a function handle (see this related answer).
The error you are getting is because you can't call o and use it as an input to fminsearch() since o is undefined. To get o, you have to first get u(x,y), plus as mentioned, fminsearch requires a function handle as an input.
You have several options that still use your standalone function, u(x,y).
1. Create a function handle
Define a function handle that calls u(x,y) but has a single argument which is a 2 x 1 vector, z = [x; y].
fh =#(z) u(z(1),z(2));
z0 = [1; 2]; % Initial Guess for z = [x; y]
[z,TC] = fminsearch(fh,z0)
2. Change the function and call it directly
The same result is possible with
[z,TC] = fminsearch(#u,z0)
if you redefine u(x,y) to be as follows:
function o=u(z)
x = z(1);
y = z(2);
% your function code here
end

How to implement a .m script in Simulink? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i have written a m-function in a script. This function script simulates behavior of a system.
Now i want to implement it in a Simulink Modell. The function has several inputs and several outputs. Actually i find the user-defined functions, but they all have one input and one output.
Do somebody now how i can implement the m.file into the simulink modell with more than one inputs and outputs?
Thank You!
All of the user defined functions allow multiple inputs.
For instance, the MATLAB Function block has a default of:
function y = fcn(u)
y = u;
Which can be changed to have 2 outputs and 3 inputs (for instance) just like any other MATLAB function:
function [out1,out2] = fcn(in1,in2,in3)
out1 = in1;
out2 = in2 + in3;

How to determine if an output is being ignored with ~ [duplicate]

This question already has an answer here:
How to determine if an output of a function-call is unused?
(1 answer)
Closed 5 years ago.
In Matlab, you can ignore an output with the following syntax:
[~, ixMax] = max(foo);
I have a function, with signature
[out, out1, out2, out3] = function foo(in1, in2, in3)
out1, out2 and out3 are optional outputs, and each is only needed in very specific (unusual) circumstances. Foo is computationally expensive, and out1/out2/out3 are all even more computationally expensive, but rely on intermediate state generated by foo. I'd like to be able to avoid computing out1/out2/out3 if the caller is using a ~ to ignore them. How can I check for that in the definition of foo?
It won't accelerate the process. The ~ is a way to the reader to tell him you won't need these outputs. It also saves the memory usage of this variable.
Matlab documentation says:
However, some functions return results that use much more memory. If you do not need those variables, they waste space on your system.
So it does not improve performance because these values are internally calculated anyway.
The book Accelerating MATLAB Performance: 1001 tips to speed up MATLAB programs by Yair M. Altman says (p187):
However, without using the ~, and if the first output is needed, the user will gain computational time by just removing the ~ and the brackets, and writing.
out = function foo(in1, in2, in3)

Automatically generating a diagram of function calls in MATLAB [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
Anybody knows of a tool that can be used to automatically build diagrams of function calls in MATLAB?
E.g. For a given function, the tool would recursively go through function calls and build a 2D graph where nodes would represent functions and directed edges would connect calling functions with called functions.
Ideally the tool could allow the user to turn on and off filters to only include user-defined functions, limit the depth of recursion, etc.
I believe Doxygen provides some similar functionality for more traditional OOP languages, but I was wondering if something like this exists already for MATLAB.
Thanks!
You can use the techniques from those other answers referenced in gnovice's comment to get a list of function dependencies as (A,B) pairs, where A calls B. Then install GraphViz and use it to generate the diagrams. You can create the .dot files from Matlab with something like this.
function createFunctionDependencyDotFile(calls)
%CREATEFUNCTIONDEPENDENCYDOTFILE Create a GraphViz DOT diagram file from function call list
%
% Calls (cellstr) is an n-by-2 cell array in format {caller,callee;...}.
%
% Example:
% calls = { 'foo','X'; 'bar','Y'; 'foo','Z'; 'foo','bar'; 'bar','bar'};
% createFunctionDependencyDotFile(calls)
baseName = 'functionCalls';
dotFile = [baseName '.dot'];
fid = fopen(dotFile, 'w');
fprintf(fid, 'digraph G {\n');
for i = 1:size(calls,1)
[parent,child] = calls{i,:};
fprintf(fid, ' "%s" -> "%s"\n', parent, child);
end
fprintf(fid, '}\n');
fclose(fid);
% Render to image
imageFile = [baseName '.png'];
% Assumes the GraphViz bin dir is on the path; if not, use full path to dot.exe
cmd = sprintf('dot -Tpng -Gsize="2,2" "%s" -o"%s"', dotFile, imageFile);
system(cmd);
fprintf('Wrote to %s\n', imageFile);
GraphViz works great for lots of other tree and graph applications, like class inheritance and dependency trees, data flow, and so on.