Getting points from an anonymous function after integration in MATLAB - matlab

I want to get value of v(U,n0) for various points in MATLAB
eq = #(q,U,n0) 2*(1-cos(2*pi*q));
hq = #(q,U,n0) ((eq)^2+2*U*n0*(eq))^(1/2);
y = #(q,U,n0) (((eq)+(U*n0))/hq)-1;
a = -0.5;
b = 0.5;
v = #(U,n0) quad(#(q) y(q,U,n0),a,b);
But I get lots of errors like
>> v(1,2)
Undefined function 'plus' for input arguments of type 'function_handle'.
Error in #(q,U,n0)(((eq)+(U*n0))/hq)-1
Error in #(q)y(q,U,n0)
Error in quad (line 72) y = f(x, varargin{:});
Error in #(U,n0)quad(#(q)y(q,U,n0),a,b)
Can anybody help me out with the errors?

You are using function handles without specifying their arguments. For example, after you define eq(q,U,n0), you use it in hq like a variable (eq) without any inputs. Whenever you use a function, you must give it inputs, so use eq(q,U,n0), not just eq.

Related

How can I Minimize this function with MATLAB?

I wrote the following function in MATLAB:
function EX_EFFICIENCY=EXERGY_EFFICIENCY_FUNCTION(CR,ER,PC,T0,P0)
I used the following order (ga):
x = ga(#EXERGY_EFFICIENCY_FUNCTION,5)
But it gets the error:
Not enough input arguments.
Error in EXERGY_EFFICIENCY_FUNCTION (line 22)
T7p=T0.*(PC.^((k-1)./k));
Error in createAnonymousFcn>#(x)fcn(x,FcnArgs{:}) (line 11) fcn_handle
= #(x) fcn(x,FcnArgs{:});
Error in makeState (line 47)
firstMemberScore = FitnessFcn(state.Population(initScoreProvided+1,:));
Error in gaunc (line 40) state =
makeState(GenomeLength,FitnessFcn,Iterate,output.problemtype,options);
Error in ga (line 398)
[x,fval,exitFlag,output,population,scores] = gaunc(FitnessFcn,nvars, ...
Caused by:
Failure in initial user-supplied fitness function evaluation. GA cannot continue.
How can I minimize this function?
What are the variables you want to minimize over? All five CR,ER,PC,T0,P0? Then you need to tell ga to use a length-5-vector and deal its elements to the input arguments of the function. Like this:
xopt = ga(#(x) EXERGY_EFFICIENCY_FUNCTION(x(1),x(2),x(3),x(4),x(5)), 5);
You can also fix some and optimize over the others of course, like this:
xopt = ga(#(x) EXERGY_EFFICIENCY_FUNCTION(x(1),x(2),PC,T0,P0), 2);
optimizes CR, ER for fixed values of PC,T0, and P0.

ODE solver producing runtime error - not enough input arguments [duplicate]

I have a use case as follows:
Inside F.m I have a function F that takes as its argument a 2 x 1 matrix x. F needs to matrix multiply the matrix kmat by x. kmat is a variable that is generated by a script.
So, what I did was set kmat to be global in the script:
global kmat;
kmat = rand(2);
In F.m:
function result = F(x)
global kmat;
result = kmat*x;
end
Then finally, in the script I have (x_0 has already been defined as an appropriate 2 x 1 matrix, and tstart and tend are positive integers):
xs = ode45(F, [tstart, tend], x_0);
However, this is causing the error:
Error using F (line 3)
Not enough input arguments.
Error in script (line 12)
xs = ode45(F, [tstart, tend], x_0);
What is going on here, and what can I do to fix it? Alternatively, what is the right way to pass kmat to F?
Firstly, the proper way to handle kmat is to make it an input argument to F.m
function result = F(x,kmat)
result = kmat*x;
end
Secondly, the input function to ode45 must be a function with inputs t and x (possibly vectors, t is the dependent variable and x is the dependent). Since your F function doesn't have t as an input argument, and you have an extra parameter kmat, you have to make a small anonymous function when you call ode45
ode45(#(t,x) F(x,kmat),[tstart tend],x_0)
If your derivative function was function result=derivative(t,x), then you simply do ode45(#derivative,[tstart tend],x_0) as Erik said.
I believe F in ode45(F,...) should be a function handle, i.e. #F. Also, you can have a look at this page of the MATLAB documentation for different methods to pass extra parameters to functions.

How to use fmincon to optimize two control vectors of a function

I have a function of 2 different vector. These are the control vector (decision variables) of the function. I want to use fmincon to optimize this function and also get the both control vector results separately.
I have tried to use handle ,#, but I got an error.
The function is:
function f = myFS(x,sv) % x is a vector (5,1)
f = norm(x)^2-sigma*(sv(1)+sv(2));
end
%% I tried to write fmincone to consider both control vectors (x and sv)
[Xtemp(:,h2),Fval, fiasco] = fmincon(#(x,sv)myFS(x,sv)...
,xstart,[],[],[],[],VLB,VUB,#(x,sv)myCon(sv),options);
Here is the error I get:
Error using myFS (line 12) Not enough input arguments.
Error in fmincon (line 564)
initVals.f =
feval(funfcn{3},X,varargin{:});
Error in main_Econstraint (line 58) [Xtemp(:,h2),Fval, fiasco] =
fmincon('myFS',xstart,[],[],[],[],VLB,VUB,#(x,sv)myCon(sv),options);
Thanks
fmincon expects your function to be of a single variable, there is no getting around that, but see:
http://se.mathworks.com/help/optim/ug/passing-extra-parameters.html
for example, if both x, cv are variables of the optimization you can combine them and then split them in the actual objective
for example
x_cv = vertcat(x, cv) and then x = x_cv(1:5); cv = x_cv(6:end)'
if cv is not a variable of the optimization, then 'freeze it' as the link above suggests

MATLAB function fminunc generates errors

I am facing an error when using the function fminunc in the context of a maximum-likelihood estimation. I am afraid that it is very straight forward however my experience with MATLAB is very limited.
The function "normal" contains the log-likelihood function. I seek to estimate the expectation and std. deviation of a normal distribution given the observations stored in the variable x.
function f = normal(X, theta)
mean = theta(1);
sigma = theta(2);
z = (X-mean)./sigma;
f = -(sum(-log(sigma) -(1/2).*z.^2 ));
I basically execute the following code:
theta = [1,1]
f = #(theta)normal(x, theta)
[est, fval, exitflag, output, grad, hessian] = fminunc('normal', x, theta)
The error is the following:
Warning: Struct field assignment overwrites a value with class "double". See MATLAB R14SP2 Release
Notes, Assigning Nonstructure Variables As Structures Displays Warning, for details.
In createOptionFeedback at 34
In prepareOptionsForSolver at 31
In fminunc at 157
Warning: Struct field assignment overwrites a value with class "double". See MATLAB R14SP2 Release
Notes, Assigning Nonstructure Variables As Structures Displays Warning, for details.
In fminunc at 203
Error using feval
Undefined function 'normal' for input arguments of type 'double'.
Error in fminunc (line 254)
f = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial user-supplied objective function evaluation. FMINUNC cannot continue.
Unfortunately the manual did not help me to fix the code. Calling
[est, fval, exitflag, output, grad, hessian] = fminunc(f, x, theta)
did not help either. What am I doing wrong?
Thank you in advance!
You have called fminunc with the wrong sintax, please refer to the documentation.
A way to fix your code is by defining the function normal to accept only one parameter: theta.
function f = normal(theta)
global X
mean = theta(1);
sigma = theta(2);
z = (X-mean)./sigma;
f = -(sum(-log(sigma) -(1/2).*z.^2 ));
and call fminunc with
global X
X = randn(100, 1); % A possible time series.
theta0 = [1,1];
[est, fval, exitflag, output, grad, hessian] = fminunc(#normal, theta0);

Error using fzero in Matlab: Undefined function or method 'det' for input arguments of type 'function_handle'

I have the same kind of problem described in this topic:
Using fzero: Undefined function or method 'isfinite' for input arguments of type 'sym'
Their answers really helped me, but I am still stuck.
I also have to find the zeros of a function of w, this function is defined in several steps:
So the only unknown is w, and I defined other objects such as:
lambda= #(w) ((16*rho(i)*A(i)*w^2*Lprime(i)^2)/(E(j)*I(i)))^0.25;
beta=#(w) lambda*b(i)^0.5;
gamma=#(w) lambda*Lprime(i)^0.5;
Then, I define a 4*4 matrix M2:
M2=#(w) [besselj(4,beta) bessely(4,beta) besseli(4,beta) besselk(4,beta);
besselj(3,beta) bessely(3,beta) besseli(3,beta) -besselk(3,beta);
besselj(2,gamma) bessely(2,gamma) besseli(2,gamma) besselk(2,gamma);
besselj(4,gamma) bessely(4,gamma) besseli(4,gamma) besselk(4,gamma)];
Then the equation to be solved is: det(M2)=0. But w=0 is one of the solutions, and I want the first non-zero solution, so I wrote:
delta = #(w) det(M2);
S(i,j)=fzero(delta,500);
Then I run the program, and Matlab says:
??? Error using ==> fzero at 235
FZERO cannot continue because user supplied function_handle ==> #(w)det(M2)
failed with the error below.
Undefined function or method 'det' for input arguments of type 'function_handle'.
Error in ==> frequencies at 57
S(i,j)=fzero(delta,500);
I also tried with the subs and the eval methods, and they don't work either, the error messages are in those cases:
??? Undefined function or method 'isfinite' for input arguments of type 'sym'.
Error in ==> fzero at 323
elseif ~isfinite(fx) || ~isreal(fx)
Error in ==> frequencies at 58
S(i,j)=fzero(#(w) subs(delta,'w',w),500);
Which is the same error as edio's I guess. And:
??? Error using ==> fzero at 307
FZERO cannot continue because user supplied function_handle ==> #(w)eval(delta)
failed with the error below.
Undefined function or method 'eval' for input arguments of type 'function_handle'.
Error in ==> frequencies at 59
S(i,j)=fzero(#(w)eval(delta),500);
Can you help me please?
Your problem appears to be that you are never evaluating your anonymous functions when you place them within other anonymous functions. For example, you define the function lambda as such:
lambda = #(w) ((16*rho(i)*A(i)*w^2*Lprime(i)^2)/(E(j)*I(i)))^0.25;
But when you use it in beta, you need to evaluate it using the input value for w, like so:
beta = #(w) lambda(w)*b(i)^0.5;
%# ^--------------Pass w to lambda to evaluate the function
As such, I believe your other anonymous functions should be defined as follows:
gamma = #(w) lambda(w)*Lprime(i)^0.5;
M2 = #(w) [besselj(4,beta(w)) bessely(4,beta(w)) besseli(4,beta(w)) ...
besselk(4,beta(w)); ...
besselj(3,beta(w)) bessely(3,beta(w)) besseli(3,beta(w)) ...
-besselk(3,beta(w)); ...
besselj(2,gamma(w)) bessely(2,gamma(w)) besseli(2,gamma(w)) ...
besselk(2,gamma(w)); ...
besselj(4,gamma(w)) bessely(4,gamma(w)) besseli(4,gamma(w)) ...
besselk(4,gamma(w))];
delta = #(w) det(M2(w));
A note about efficiency...
There is a GLARING efficiency problem I'm noticing here. By using anonymous functions instead of any other type of function (primary functions, nested functions, or subfunctions) you are going to end up evaluating the same function with the same input multiple times over.
For example, each time you evaluate M2 to create your matrix you will be evaluating both beta and gamma 8 times with the same input! Notice the improvement you could make by placing M2 in a function and passing as input w and the two function handles beta and gamma:
function newMatrix = M2(w,betaFcn,gammaFcn)
bw = betaFcn(w); %# Evaluate the beta function once
gw = gammaFcn(w); %# Evaluate the gamma function once
newMatrix = [besselj(4,bw) bessely(4,bw) besseli(4,bw) besselk(4,bw); ...
besselj(3,bw) bessely(3,bw) besseli(3,bw) -besselk(3,bw); ...
besselj(2,gw) bessely(2,gw) besseli(2,gw) besselk(2,gw); ...
besselj(4,gw) bessely(4,gw) besseli(4,gw) besselk(4,gw)];
end
And your new delta function would look like this:
delta = #(w) det(M2(w,beta,gamma));
Hi thank you very much for your help.
It works, but the last line has to change, obviously (it still took me 10 minuts for figure it out):
lambda= #(w) ((16*rho(i)*A(i)*w^2*Lprime(i)^2)/(E(j)*I(i)))^0.25;
beta=#(w) lambda(w)*b(i)^0.5;
gamma=#(w) lambda(w)*Lprime(i)^0.5;
M2=#(w) [besselj(4,beta(w)) bessely(4,beta(w)) besseli(4,beta(w)) besselk(4,beta(w));
besselj(3,beta(w)) bessely(3,beta(w)) besseli(3,beta(w)) -besselk(3,beta(w));
besselj(2,gamma(w)) bessely(2,gamma(w)) besseli(2,gamma(w)) besselk(2,gamma(w));
besselj(4,gamma(w)) bessely(4,gamma(w)) besseli(4,gamma(w)) besselk(4,gamma(w))];
delta = #(w) det(M2(w));
S(i,j)=fzero(#(w) delta(w),500);
And now it is really faster than before, in another case where the function solve could handle the resolution, it took like 10 seconds for each loop, now it's like 0.06 seconds
I will try your other solution to see the improvements.
Thank you a lot.