Pass user-input number of variables into Matlab function handle - matlab

I am looking to use the fminsearch function for minimization. According to the documentation, fminsearch requires a function handle and initial parameter estimate.
However, I have been struggling to create a function handle that accepts a variable number of inputs. This is an example of how I would like my code to behave:
for i = 1:M
fhandle = #(x)(x(i) + #fhandle)
end
In this example, the final fhandle is the sum of all x. Is there any way to implement this and optimize all x values such that fhandle is minimized?

Function handles accept varargin. So your exemple can be rewriten to accept a variable number of inputs:
fhandle = #(varargin) sum([varargin{:}])
and then
>> fhandle(1)
ans =
1
>> fhandle(1,2)
ans =
3
>> fhandle(1,2,3)
ans =
6
Best,

Related

Use a function as input for another function

Hi I am new to matlab so not familiar with its grammar.
I want to write a function to solve some functions using specific algo.
What I want to do is to write a function using another function which I want to slove as input.
For example, if I want to get the root of x^2 - 1 = 0 ,I need to plug in this function as in input.
my code is like
function [y] = brent(f, x0, x1, max_iter, tolerance)
fx0 = f(x0)
fx1 = f(x1)
......
end
f is the function I want to solve. My question is how should I write the code so the function 'brent' can use the function 'f' to calculate the values at specific points.
ex. In the second line, I need to get the value of f(x0) (x0 is a point).
Matlab talks about function handles. Those can be input parameter as anything:
Write your main function:
function a = func(f,x)
a = f(x) + 7;
Define your function to be input, and call 'normally'
>> myfun = #(x) x^2-1;
>> func(myfun,3)
ans =
15
>> func(#sin,0)
ans =
7
see:
https://se.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html

MATLAB: Why is the anoynomous function missing `(t,y)` here?

function yprime=example1(t , y)
yprime=cos(t)./(2*y-2);
Then type
>> [t,y] =ode45(#example1, [0, 4*pi],3);
>> plot(t , y)
On the line ode45(#example...). Why isn't it ode(#45(t,y)example...)?. How can [0, 4*pi] and 3 be passed into the derivative (i.e. example1) if the input is missing?
The # operator can create two (maybe more) different types of handles: simple and anonymous. A simple function handle is one that directly references a function file and has no other levels of in-direction. An anonymous function is a handle that is itself a (very simple) function and possesses its own workspace for constant storage, closures, and other purposes. The difference can be seen using the functions function:
>> f1 = #example1
f1 =
#example1
>> f2 = #(t,x) example1(t,x)
f2 =
#(t,x)example1(t,x)
>> functions(f1)
ans =
function: 'example1'
type: 'simple'
file: 'C:\Development\example1.m'
>> functions(f2)
ans =
function: '#(t,x)example1(t,x)'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
within_file_path: '__base_function'
Anonymous functions add a bit of overhead due to them being more than just pointers to functions and are therefore only really needed if you're parameterizing functions.
Regardless of the creation, ode45 and its kin will always attempt to pass the t and y argument pair to the handle you pass it via feval, and the argument list is only required if you are using anonymous functions versus direct file handle references.
That is just how the ode45 function in MATLAB works.
ode45(#function, [start, end] for t, initial value of y).
So in the example above, function is example1, t0 will be 0, tn (last point) will be 4*pi, and the initial value of y is 3.
The most important part of using ode45 is properly setting up the function. Notice how the function is set for the dy/dt. Because of this, given an initial point, it can generate the rest of the points for y at time t because it can calculate the change in y as t increases.

fminsearch with vector inputs

I want to minimize this function:
function [GCV2]=GCV(y,x,k)
[n, p]=size(x);
A=(x'*x+k*eye(p));
A=A\x';
A=x*A;
I_mat=eye(n);
num2=(I_mat-A);
num2=num2*y;
num2=norm(num2);
num2=num2^2;
num2=num2/n;
%(norm((I_mat-A)*y)^2)/n;
den2=(I_mat-A);
den2=trace(den2);
den2=den2/n;
den2=den2^2;
GCV2=num2/den2;
end
The x and y values are 13-by-4) and 13-by-1 arrays, respectively, and these values are already defined in the Matlab workspace. I want to optimize on the k value so that the function value GCV is minimized.
The parameter being optimized as well as the output are scalar so fminsearch should be appropriate.
But I can't get it to run?
I've tried several methods, the latest being:
k_min = fminsearch(#GCV,(x;y;0));
??? k_min = fminsearch(#GCV,(x;y;0));
|
Error: Unbalanced or unexpected parenthesis or bracket.
What am I doing wrong?
Looks like you're learning about anonymous functions. fminsearch minimizes a single variable (which may be a vector). Your objective function must therefore have only one input. You have a function, GCV, that takes three inputs. Two are static and are defined in the workspace outside of the minimization, while k is the one to be minimized. To create a function with one input from GCV, you can use any anonymous function, taking care to specify which variables are parameters:
x = ...
y = ...
k0 = 0;
k_min = fminsearch(#(k)GCV(y,x,k),k0);
The second input to fminsearch is the starting parameter (i.e. k0), so specify a starting value of k. Then you can define an anonymous helper function and optimize on that:
>> % define x,y
>> GCVk = #(k) GCV(y,x,k);
>> k0 = 0;
>> k_min = fminsearch(GCVk,k0)
There is probably another way to do this, but this is one of the listed ways of passing additional parameters for the optimizer.
And since there are no bonus points for being first, how about humor. Let's have an example:
>> x=1; y=1;
>> GCVk = #(k) x+y+k; k0=0;
>> k_min = fminsearch(GCVk,k0)
Exiting: Maximum number of function evaluations has been exceeded
- increase MaxFunEvals option.
Current function value: -316912650057057490000000000.000000
k_min =
-3.1691e+26
Found it - the lowest number (minus 2) in the world! Profit?

defining different cases for function im matlab (symfun)

i want to create a function (symfun), and i want to divide it to cases, i.e if t> then then answer will be a and if t<0 the answer will be b.
the thing is, that matlab wont allow me to put an if statements after a sym function.
>> l = symfun(0, [m]);
>> l(m) = if m>0 3
also i tried to create a function:
function [x1] = xt_otot_q3(t)
and tried to connect between the two functions:
>> l(m) = xt_otot_q3(m)
Conversion to logical from sym is not possible.
is there any way to break a symfun into cases?
Not sure that I understand what you want.
This code 'combines' the functions symfun and xt+otot_q3 defined below:
function test;
m=randn(4); % N(0,1) random numbers
l=xtotot_q3(symfun(0,m)) % combine xt_otot_q3 and symfun
l=symfun(0,xtotot_q3(m)) % combine symfun and xt_otot_q3
return
function lval=symfun(thr,rval);
lval=ones(size(rval)); % output, size of input, = 1
lval(rval<thr)=-1; % output = -1 if input < thr
return
function lval=xtotot_q3(rval);
lval=3*rval+1; % some function, in this case 3 * input + 1
return
You can save the whole bit as test.m and then call test from the matlab prompt. Maybe if you start with this then you can modify it to fit your needs.

Merging function handles in MATLAB

I'm currently coding a simulation in MATLAB and need some help in regards to an issue that I've been having.
I'm working on a problem where I have n separate anonymous function handles fi stored in cell array, each of which accepts a 1×1 numeric array xi and returns a 1×1 numeric array yi.
I'm trying to combine each of these anonymous function handles into a single anonymous function handle that accepts a single n×1 numeric array X and returns a single n×1 numeric array Y, where the i-th elements of X and Y are xi and yi = fi (xi), respectively.
As an example, let n = 2 and f_1, f_2 be two function handles that input and output 1×1 arrays and are stored in a cell array named functions:
f_1 = #(x_1) x_1^2
f_2 = #(x_2) x_2^3
functions = {f_1, f_2}
In this example, I basically need to be able to use f_1 and f_2 to construct a function handle F that inputs and outputs a 2×1 numeric array, like so:
F = #(x) [f_1(x(1,1)); f_2(x(2,1))]
The question is how to generalize this for an arbitrary number n of such functions.
It is difficult to define such a function using the inline #()-anonymous
syntax (because of the requirement for the function’s body to be
an expression).
However, it is possible to define a regular function that runs over
the items of a given vector and applies the functions from a given
cell array to those items:
function y = apply_funcs(f, x)
assert(length(f) == length(x));
y = x;
for i = 1 : length(f)
y(i) = feval(f{i}, x(i));
end
end
If it is necessary to pass this function as an argument to another
one, just reference it by taking its #-handle:
F = #apply_funcs
This can be solved using a solution I provided to a similar previous question, although there will be some differences regarding how you format the input arguments. You can achieve what you want using the functions CELLFUN and FEVAL to evaluate your anonymous functions in one line, and the function NUM2CELL to convert your input vector to a cell array to be used by CELLFUN:
f_1 = #(x_1) x_1^2; %# First anonymous function
f_2 = #(x_2) x_2^3; %# Second anonymous function
fcnArray = {f_1; f_2}; %# Cell array of function handles
F = #(x) cellfun(#feval,fcnArray(:),num2cell(x(:)));
Note that I used the name fcnArray for the cell array of function handles, since the name functions is already used for the built-in function FUNCTIONS. The colon operator (:) is used to turn fcnArray and the input argument x into column vectors if they aren't already. This ensures that the output is a column vector.
And here are a few test cases:
>> F([2;2])
ans =
4
8
>> F([1;3])
ans =
1
27
#you can try
f=#(x)[x(1)^2;x(2)^3]
>>f([1,2])
ans =
1
8
>>f([2,3])
ans =
4
27