Function as a parameter - matlab

I have a function in a .m file:
function [func diff1 diff2]=fun(x)
func=(3*x^3)+6;
diff1=(3*(x+0.00000001)^3-3*((x)^3))/0.00000001;
diff2=(3*((x+0.00000001)^3)-2*3*(x^3)+3*(x-.00000001)^3)/(.00000001^2);
end
In the second function I want to be able to pass in the function as a parameter. I keep getting
"Attempted to access fun(3); index out of bounds because numel(fun)=1."
Does anyone have any ideas?
function [x,N,fval]=halley(fun,guess,tol);
fval=fun(guess);
end

You need to pass a function handle when calling halley:
halley(#fun, 3, 0.1)

Related

List subfunctions defined in function file within calling environment

I have a function defined like the following in a .m file:
function main_fn()
...
end
function sub_fn1()
...
end
function sub_fn2()
....
end
...
function sub_fnN()
...
end
i.e. standard structure with main function first followed by subfunctions accessible by the main function when it is called.
I know that you can use whos within the function calling environment to return the variables stored in the function call stack. I would like to retrieve the sub-functions defined within the function file, and return them as a cell array of function handles.
Is this possible?
EDIT: the answer by #nirvana-msu has made my original request possible. However, now I find that it is more convenient to store these functions in a struct, so that I can refer to them by name:
For example:
fcn =
struct('sub_fn1', #sub_fn1, ...
'sub_fn2', #sub_fn2, ...
...
)
EDIT 2:
It is simply to convert the cell array obtained in the answer to a struct, simply use func2str:
fcns = cell2struct(fncs, cellfun(#func2str, fncs, 'uni', 0));
Use localfunctions - introduced in R2013b:
function main_fn()
fcns = localfunctions();
end
function sub_fn1()
end
function sub_fn2()
end
function sub_fnN()
end
It returns a cell array of function handles to all local functions in your file:
fcns =
#sub_fn1
#sub_fn2
#sub_fnN

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

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'.

an error received while executing my function?

When I execute the following:
function [ x ] = addya( varargin )
x=varargin{1};
t=varargin{1};
if(nargin>1)
for i=2:nargin
t=t+varargin(i);
end;
end
x=t;
The error i am getting is:
addya(1,1) ??? Undefined function or method
'addya' for input arguments of type 'double'.
please suggest changes and errors.
Make sure this function is saved in a file called addya.m.
Moreover, as mentioned by il_raffa there's a typo - inside the loop: you should access varargin using {}.
The following code works for me when saved as addya.m:
function [ x ] = addya( varargin )
x=varargin{1}; %// Why is this needed?
t=varargin{1};
if(nargin>1)
for i=2:nargin
t=t+varargin{i};
end;
end
x=t;
Also, I would suggest to refrain from using i as a loop index due to possible complication with complex numbers.

MATLAB : dynamic variables not updated directly in the workspace

I have a problem with some varaibles.
I create variables dynamically in a loop.
for i=1:nbr
assignin('base', ['x_',num2str(i)],0)
end
And after, I would like to put the result of my function in these variables. But the variables in the base of the workspace are not updated directly so I have an error "Undefined function or variable". How can I fix my problem ?
for i=1:nbr
['x_',num2str(i)]= fonction(input);
end
Thank you in advance
Best regard
Instead, use a cell array:
x{i} = function(input);
Then return the entire cell array back to the caller, so that you never need to use assignin. The whole function body would look like this:
function x = myfunction(someinput)
for i=1:nbr
x{i} = someotherfunction(input);
end
% Cell array x is returned from the function

passing a colon as argument of a function in matlab

I would like to know if it's possible to use a colon ":" as argument of a function.
Something like that:
function y=func(x)
if x is a colon
do this
else
do that
end
Also is it possible to pass the key work end as argument of a function, and also 1:end, 3:end-5, etc...
I doubt it's possible, but I would like to be sure.
Also, I get a weird error when I pass "1:end" as argument of a function, it produces no error, but inside the function, no argument is assigned (not even the other arguments). Do someone know what happens?
You can override both for your own classes:
classdef MyClass
properties(Access=public)
data
end
methods
function out = end(A,k,n)
disp(A);
disp(k);
disp(n);
out = [];
end
function B = subsref(A,S)
disp(S);
B = [];
end
end
end
As for functions, I never heard of such a functionality.
No, it's not possible to pass a colon as an argument (it doesn't make any sense).