How to use pcg with a function in MATLAB - matlab

I am going to solve an inverse problem, AX=b, using conjugate gradient method in MATLAB. I want to use pcg function in MATLAB and as I know instead of matrix A I can use a function.
I have a function for example afun which has some entries. In the documents, I have seen that the afun function is entered in pcg function without entries, however, when I do the same, the error not enough input arguments appears. I use a code like this:
b = afun(ent1,ent2);
x = pcg(#afun,b,tol,max_iter);
How should I use my function in pcg?

According to the documentation, the function handle should the have the signature afun(x) and return A*x.
Your function apparently takes two inputs... You need to use a anonymous function to wrap the call, something like this:
% I dont know what these ent1/ent2 represent exactly,
% so you must complete the ".." part first
fcn = #(x) afun(x, ..)
% now you can call PCG
x = pcg(fcn, b, tol, maxiter);
There is a doc page explaining how to parameterize functions to pass extra args using function handles.

Related

How to write an anonymous function with a variable number of output arguments?

Using deal we can write anonymous functions that have multiple output arguments, like for example
minmax = #(x)deal(min(x),max(x));
[u,v] = minmax([1,2,3,4]); % outputs u = 1, v = 4
But if you want to provide a function with its gradient to the optimization function fminunc this does not work. The function fminunc calls the input function sometimes with one and sometimes with two output arguments. (EDIT: This is not true, you just have to specify whether you actually want to use the gradient or not, using e.g. optimset('SpecifyObjectiveGradient',true). Then within one call it always asks for the same number of arguments.)
We have to provide something like
function [f,g] = myFun(x)
f = x^2; % function
g = 2*x; % gradient
which can be called with one or two output arguments.
So is there a way to do the same inline without using the function keyword?
Yes there is, it involves a technique used in this question about recursive anonymous functions. First we define a helper function
helper = #(c,n)deal(c{1:n});
which accepts a cell array c of the possible outputs as well as an integer n that says how many outputs we need. To write our actual function we just need to define the cell array and pass nargout (the number of expected output arguments) to helper:
myFun = #(x)helper({x^2,2*x,2},nargout);
This now works perfectly when calling fminunc:
x = fminunc(myFun,1);
The OP's solution is good in that it's concise and useful in many cases.
However, it has one main shortcoming, in that it's less scalable than otherwise possible. This claim is made because all functions ({x^2,2*x,2}) are evaluated, regardless of whether they're needed as outputs or not - which results in "wasted" computation time and memory consumption when less than 3 outputs are requested.
In the example of this question this is not an issue because the function and its derivatives are very easy to compute and the input x is a scalar, but under different circumstances, this can be a very real issue.
I'm providing a modified version, which although uglier, avoids the aforementioned problem and is somewhat more general:
funcs_to_apply = {#(x)x.^2, #(x)2*x, #(x)2};
unpacker = #(x)deal(x{:});
myFun = #(x)unpacker(cellfun(#(c)feval(c,x),...
funcs_to_apply(1:evalin('caller','nargout')),...
'UniformOutput',false)...
);
Notes:
The additional functions I use are cellfun, evalin and feval.
The 'UniformOutput' argument was only added so that the output of cellfun is a cell (and can be "unpacked" to a comma-separated list; we could've wrapped it in num2cell instead).
The evalin trick is required since in the myFun scope we don't know how many outputs were requested from unpacker.
While eval in its various forms (here: evalin) is usually discouraged, in this case we know exactly who the caller is and that this is a safe operation.

How to call a custom function with exponentiation for every element of a matrix in GNU Octave?

Trying to find a way to call the exponentiation function ( ^ ) used in a custom function for every item in a matrix in GNU Octave.
I am quite a beginner, and I suppose that this is very simple, but I can't get it to work.
The code looks like this:
function result = the_function(the_val)
result = (the_val - 5) ^ 2
endfunction
I have tried to call it like this:
>> A = [1,2,3];
>> the_function(A);
>> arrayfun(#the_function, A);
>> A .#the_function 2;
None of these have worked (the last one I believe is simply not correct syntax), throwing the error:
error: for A^b, A must be a square matrix
This, I guess, means it is trying to square the matrix, not the elements inside of it.
How should I do this?
Thanks very much!
It is correct to call the function as the_function(A), but you have to make sure the function can handle a vector input. As you say, (the_val - 5)^2 tries to square the matrix (and it thus gives an error if the_val is not square). To compute an element-wise power you use .^ instead of ^.
So: in the definition of your function, you need to change
result = (the_val-5)^2;
to
result = (the_val-5).^2;
As an additional note, since your code as it stands does work with scalar inputs, you could also use the arrayfun approach. The correct syntax would be (remove the #):
arrayfun(the_function, A)
However, using arrayfun is usually slower than defining your function such that it works directly with vector inputs (or "vectorizing" it). So, whenever possible, vectorize your function. That's what my .^suggestion above does.

Matlab - Invoking a function handle with generic parameter list

I'm playing around with numerical integration methods and would like to have a function
myIntegrator(f,fParams)
In which I'll implement a numerical integration.
As f might require any number of parameters, I'm looking for a generic way for myIntegrator() to accept the function handle (#f) and invoke it using fParams.
To better clarify, I would like to call myIntegrator, once with the following #g and then with #h (just some numerical functions):
g(x,y)
h(x)
And I'm wondering if there is a single line of code I could use in myIntegrator that would perform :
myIntegrator(f,fParams)
invoke(f,fParams)
end
and would work both for
myIntegrator(#g,[x,y])
and
myIntegrator(#h,[x])
Your help is greatly appreciated!
Have you considered using variable number of input arguments varargin?
function myIntegrator( f, varargin )
%
%
fprintf(1, 'function f got %d arguemnts\n', nargin );
% calling f with its arguments
f( varargin{:} );
See the manual on varargin for more info.
Now you can call it
myIntegrator( #g, x, y );
as well as
myIntegrator( #h, x );
I think you're looking for feval:
>> feval(#cos, pi)
ans =
-1
feval accepts any number of inputs, which are then given as inputs to the function f. In addition, feval works for both function handles and functions defined by a string.
A good mechanism to pass on arguments is the varargin method, with cell-expansion in the call to f, as described by Shai.
However, I would advise you to forget about all this and take another route; anonymous functions:
[t,y] = myIntegrator(#(t,x) f(a,t,c,x,y), ...)
[t,y] = myIntegrator(#(t,x) g(x,y,z,u,v,t), ...)
Integrators (if by that you indeed mean solvers for ODEs; otherwise, they're called quadrature methods) normally only input time t and state variable x into your differential equation. That's also how you would write it mathematically.
Any other parameters the DE might need (constants, data, filenames, ...) are not the responsibility of the integrator to pass on; that is the responsibility of the caller. The integrator should not have to know about any specifics of your function, nor have a mechanism that more-or-less duplicates something that's already built-in to MATLAB; it violates the KISS principle.
This shift of responsibility I'm talking about is accomplished by the simple example I gave above. Have a look at how to use ode45 for more details, or this page which the MATLAB documentation on this matter often refers to.

Trick matlab into thinking gpuArray is scalar

I have following function which I would like to apply to each element:
function result = f(a, b, bs)
% Simplified code
result = a
for i=0:bs
result = dosomething(result, b(i))
end
end
% Use
arrayfun(#result, gpuArray(A), gpuArray(B), size(B));
Is there a way of 'tricking' MATLAB into thinking b is scalar for purpose of passing to function?
Unfortunately, there's currently no way to do this for two reasons: firstly, the ARRAYFUN implementation for gpuArrays always insists that inputs are either scalar or all of the same size. Secondly, the gpuArray ARRAYFUN body does not currently support either indexing or anonymous functions that refer to variables from the outer scope.
The only way to do it is to use bsxfun function:
C = bsxfun(f, A, B') % A is column vector
is more or less equivalent to
C(i,j) = f(A(i,1), B(j,1))
Other useful function is repmat.
Then the series of matrices and vectors are JITted so there is in effect no O(MN) space penalty (checked by nvidia-smi).
I'm not entirely sure what you want to do, but I suspect that you want the whole of array B to be passed into the function on each call to result. The best way of achieving this would be to use an anonymous function something like so (untested code):
arrayfun( #(a_in) result(a_in, gpuArray(B), size(B)), gpuArray(A) );
What this should do is to make an anonymous function which only takes one argument (a_in), and calls result (actually f in your function header), with the full B array, regardless of the value of a_in.
So on each iteration of arrayfun, result will be called using just one slice of A, but the whole of B.
A more syntaxically explicit way of writing the above code would be as follows:
my_anon_fun = #(a_in) result(a_in, gpuArray(B), size(B));
arrayfun( my_anon_fun , gpuArray(A) );
A disclaimer: code is untested, and I have little experience with code using gpuArray so this may not apply.

Passing a strange function handle to MATLAB ode solvers - What does this code mean?

I know how to use ode15s or other ode solver in MATLAB, what I'm not sure about, is this code(from CellML) that seems vague to me:
[VOI, STATES] = ode15s(#(VOI, STATES)computeRates(VOI, STATES, CONSTANTS), tspan, INIT_STATES, options);
More specifilcly, what is the meaning of the following (?):
#(VOI, STATES)computeRates(VOI, STATES, CONSTANTS)
The header of the function, "computeRates", is the following:
function [RATES, ALGEBRAIC] = computeRates(t, STATES, CONSTANTS)
I know "#computeRates" meanse the handle of the function, but what is the meaning of
#(VOI, STATES)computeRates(VOI, STATES, CONSTANTS)
Why has it put (VOI, STATES) between # and "computeRates" ?
By the way, According the MATLAB help, if we want to integrate of the following function:
function dy = rigid(t,y)
dy = zeros(3,1); % a column vector
dy(1) = y(2) * y(3);
dy(2) = -y(1) * y(3);
dy(3) = -0.51 * y(1) * y(2);
we only need to write:
options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
[T,Y] = ode45(#rigid,[0 12],[0 1 1],options)
As R. M. correctly points out, what you are seeing used in that code is an anonymous function. Creating one is done in the following way:
fhandle = #(arglist) expr
Where arglist is a list of input arguments that are used in the computation of the function expression expr.
What you may be confused about is why the code requires that an anonymous function be created instead of just using a function handle for an existing function. The MATLAB solver routines like ode15s and ode45 will only pass two inputs to the function handle passed to them: a scalar t and a column vector y. If you have a situation where you want more parameters to be passed to the function to define its behavior, you have to supply the function with those parameters in other ways as described in the documentation for parameterizing functions.
Anonymous functions are one way to do this. In your example, you can see that the function computeRates takes a third argument CONSTANTS that supplies the function with extra parameters. When the anonymous function is made, this third input is frozen at the value(s) it contained at that moment. The anonymous function therefore acts as a wrapper that makes a three-input function behave like a two-input function so that it can be used by the solver routines, supplying the wrapped function with the extra inputs it needs that the solver routines can't pass to it.
Those are called anonymous functions, and let you create short, nifty functions on the fly without having to create a separate m file. The two variables between the parentheses after the # symbol are the inputs to the function. What follows it is the definition of the function. For example,
f=#(x,y)x+y;%# define an anonymous function to add the two inputs
f(2,3)
ans =
5