Save values that are calculated in a function for each iteration of fminsearch - matlab

I want to find the Minimum of a function using
[x,fval] = fminsearch(#(param) esm6(param,identi),result(k,1:end-1),options)
now for each Iteration step i want some values that the function 'esm6' calculates to be saved in an Array. I tried the following:
In the first line of the function i wrote
identi.sim.i_optiIter = identi.sim.i_optiIter + 1;
to have an iteration-variable counting the iteration steps of fminsearch. And later to catch the values that I need I used
identi.sim.guete_werte.gew(identi.sim.i_optiIter,:,:) = y_sim;
identi.sim.guete_werte.ungew(identi.sim.i_optiIter,:,:) = y_sim_ungew;
and to make sure that I use the new values of the identi-struct for the next function call, I wrote this at the end of the function:
assignin('base','identi',identi);
Now unfortunatly it doesn't do what I wanted it to do. Can anyone help me with this?
EDIT:
I made another attempt on it, using an Output function. I extendend my Options like this:
options = optimset('Display','iter','MaxIter',3,'OutputFcn',#outfun);
But now the Problem is that i cannot figure out where to put this outfun. The outfun Looks like this:
function stop = outfun(x,optimvalues,state,iteration,y_sim,y_sim_ungew)
stop = false;
if state == 'iter'
guete_werte.gew(iteration,:,:) = y_sim;
guete_werte.ungew(iteration,:,:) = y_sim_ungew;
end
end
Now the Problem with it is, that i can not put it in the file, where i call the fminsearch, because that is a script. If i put the outputfunction into a separate .m-function file, it is not able to Access the variables of the esm6 function. And if I add it to the esm6-function file, matlab can't find the function and says
??? Error using ==> feval Undefined function or method 'outfun' for
input arguments of type 'struct'.

Related

Matlab functions not 'posting' variables to workspace

I'm using some user generated functions in MatLab. It'll be quicker if I don't post my actual code here so I'll summarize.
I have two functions. Each of them exist in their own files saved under their proper names. They can be called and work correctly. Lets say function1 is:
function [Output1] function1=(a,b)
Output1=a+b
end
function [Output2] function2=(a,Output1)
Output2=a+Output1
end
new script file
a=2;
b=3;
function1(a,b);
function2(a,Output1);
This doesn't work, because function1 isn't posting Output1 into the workspace. How do I make it do that?
Check this tutorial. This is how you are supposed to write a function.
function Output1 = function1(a, b)
Output1 = a + b;
end
Then your second function will get the input like this.
function Output2 = function2(a, Output1)
Output2 = a + Output1;
end
Of course you need to store answers of functions into variables to have them stored in the workspace.
aa=2;
bb=3;
Output11 = function1(aa,bb);
Output22 = function2(aa,Output11);
If you don't use Output11 and Output22, functions will store their result into ans variable in the workspace. And obviously, apart from the fact that you cannot pass the variable to the second function as Output1, second function will overwrite the ans.

Passing a variable out of local functions

I'm having some trouble with local functions within my code so I've pasted a simple example below:
function [avg,testvar] = test(x) %Warning
n = length(x);
avg = mymean(x,n);
end
function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end
One can probably see what I'm attempting; to pass testvar out of the local functions. However Matlab returns the warning:
"The function return value 'testvar' might be unset"
with respect to the line I've commented "%Warning".
What's the best way of getting around this?
You need to specify the value of the second output of test(). Otherwise how can MATLAB know what its value is supposed to be? It doesn't know the second output of mymean() should be routed to the second output of test(). Perhaps this will solve your problem.
function [avg,testvar] = test(x) %Warning
n = length(x);
[avg, testvar] = mymean(x,n);
end
function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end
The variables between brackets after function are the output variables.
In your first function, you did not assign any value to testvar hence the warning. If you add testvar = 123; in the first function, the warning goes away. Or you can remove testvar from the output variables, leaving:
function avg = test(x)

How to write a function that does not throw a "wrong number of arguments" error

I am trying to write a minimal function that can be called with a variable number of arguments but that will not throw a wrong number of arguments error if miscalled.
Here is where I start from :
function varargout=fname(varargin)
% FNAME
% Usage: output=fname(input)
% Arguments check
if(nargin~=1 || nargout~=1)
disp('Function fname requires one input argument');
disp('and one output argument');
disp('Try `help fname`');
varargout(1:nargout)={0};
return;
end
input=varargin{1};
output=input;
varargout(1)={output};
end
However this does not work as I would like it to. Is there a way to write a function that :
never throw a "wrong number of arguments" error (so that the rest of the execution can continue)
accepts variable number of input and output arguments and checks them inside the function
(maybe more tricky) if the number of input / output arguments is not correct, does not replace the value of the provided output arguments (so that any misplaced call does not erase the previous value of the output argument)
I am open to any suggestions / other methods.
Thank you for your help.
UPDATE: thanks to #Amro for his answer, I guess what I miss here is either a call by address of reference for Matlab functions or a way to interrupt a function without returning anything and without stopping the rest of the execution.
Here is one way to implement your function:
function varargout = fname(input,varargin)
%# FNAME
%# Usage: output=fname(input)
%%# INPUT
if nargin<1
varargout(1:nargout) = {[]};
warning('Not enough input arguments.'), return
end
if ~isempty(varargin)
warning('Too many input arguments.')
end
%%# YOUR CODE: manipulate input, and compute output
output = input;
%%# OUTPUT
varargout{1} = output;
if nargout>1
warning('Too many output arguments.')
varargout(2:nargout) = {[]};
end
end
Obviously you can customize the warning messages to your liking...
Also, if you want your function to simply print the message instead of issuing warnings, replace all WARNING calls with simple DISP function calls.
Examples of function call:
fname()
fname(1)
fname(1,2)
x = fname()
x = fname(1)
x = fname(1,2)
[x,y] = fname()
[x,y] = fname(1)
[x,y] = fname(1,2)
The above calls execute as expected (showing warning messages when applicable). One caveat though, in the last three calls, if the variable y already existed in the workspace prior to the calls, it would be overwritten by the empty value y=[] in each...
If I understand your question correctly, then the answer is no. If a caller calls a function like this:
[a, b, c] = fname('foo');
then fname is required to return (at least) three outputs. There's no way to tell MATLAB that it should leave b and c alone if fname only returns one output.

Passing matrices from function to function in MATLAB

I'm pretty new to MATLAB and I have a simple question. What if I have the following structured functions:
function[A] = test(A)
test1(A);
test2(A);
end
function test1(A)
#% do something with A
end
function test2(A)
#% do something else with the newly modified A
end
How do I pass around A from function to function keeping it's modified nature? (Suppose A is a matrix)
EDIT: let's make the situation a little simpler. Suppose my main function is:
function[a]=test(a)
test1(a);
#%test2(a);
end
and test1() is defined as:
function[a] = test1(a)
a=5;
end
Then, I call the function test with test(3), and I want it to report ans = 5, yet it still reports ans = 3.
Thanks!
Variables in MATLAB are passed using "call by value" (with some exceptions), so any value that you pass to a function and modify has to be returned from the function and either placed in a new variable or the old variable overwritten. Returning the value of a variable from a function is simple: you just place the variable name in the output argument list for the function.
For your example, you would do this:
function A = test(A)
A = test1(A); %# Overwrite A with value returned from test1
A = test2(A); %# Overwrite A with value returned from test2
end
function A = test1(A) %# Pass in A and return a modified A
#% Modify A
end
function A = test2(A) %# Pass in A and return a modified A
#% Modify A
end
One thing to be aware of is variable scope. Every function has its own workspace to store its own local variables, so there are actually 3 unique A variables in the above example: one in the workspace of test, one in the workspace of test1, and one in the workspace of test2. Just because they are named the same doesn't mean they all share the same value.
For example, when you call test1 from test, the value stored in the variable A in test is copied to the variable A in test1. When test1 modifies its local copy of A, the value of A in test is unchanged. To update the value of A in test, the return value from test1 has to be copied to it.
Return the object from the function and then pass it on to the next function.

routine to either evaluate code or transmit via udp

I have a set of code that, depending on how the program is initiated, will either be executed locally or sent to a remote machine for execution. The ideal way I imagine this could work would look something like the following:
line_of_code = 'do_something_or_other();';
if execute_remotely
send_via_udp(line_of_code);
else
eval(line_of_code);
end
The thing is, I know that the eval() function is ridiculously inefficient. On the other hand, if I write out line_of_code in each section of the if block, that opens the door for errors. Is there any other way that I can do this more efficiently than by simply using eval()?
EDIT: After more consideration and some discussion in the comments, I have my doubts that function handles can be transmitted via UDP. I'm therefore updating my answer, instead suggesting the use of the function FUNC2STR to convert the function handle to a string for transmission, then using the function STR2FUNC to convert it back to a function handle again after transmission...
To get around using EVAL, you can use a function handle instead of storing the line of code to be executed in a string:
fcnToEvaluate = #do_something_or_other; %# Get a handle to the function
if execute_remotely
fcnString = func2str(fcnToEvaluate); %# Construct a function name string
%# from the function handle
send_via_udp(fcnString); %# Pass the function name string
else
fcnToEvaluate(); %# Evaluate the function
end
The above assumes that the function do_something_or_other already exists. You can then do something like the following on the remote system:
fcnString = receive_via_udp(); %# Get the function name string
fcnToEvaluate = str2func(fcnString); %# Construct a function handle from
%# the function name string
fcnToEvaluate(); %# Evaluate the function
As long as the code (i.e. m-file) for the function do_something_or_other exists on both the local and remote systems, I think this should work. Note that you could also use FEVAL to evaluate the function name string instead of converting it to a function handle first.
If you need to create a function on the fly, you can initialize fcnToEvaluate as an anonymous function in your code:
fcnToEvaluate = #() disp('Hello World!'); %# Create an anonymous function
And the code to send, receive, and evaluate this should be the same as above.
If you have arguments to pass to your function as well, you can place the function handle and input arguments into a cell array. For example:
fcnToEvaluate = #(x,y) x+y; %# An anonymous function to add 2 values
inArg1 = 2; %# First input argument
inArg2 = 5; %# Second input argument
cellArray = {fcnToEvaluate inArg1 inArg2}; %# Create a cell array
if execute_remotely
cellArray{1} = func2str(cellArray{1}); %# Construct a function name string
%# from the function handle
send_via_udp(cellArray); %# Pass the cell array
else
cellArray{1}(cellArray{2:end}); %# Evaluate the function with the inputs
end
In this case, the code for send_via_udp may have to break the cell array up and send each cell separately. When received, the function name string will again have to be converted back to a function handle using STR2FUNC.