Nonlinear square optimization task in matlab - matlab

let us suppose that we have following task:Find the optimal value of weights
so that minimize following equation
where var-means variance of given x1 variable, also we have constraint that sum of these weights should be equal to 1
i have initialized anonymous function and weights for initial points
w=[0.5; 0.5];
>> f=#(x1,x2) (w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
f =
#(x1,x2)(w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
i think i should use function fmincon,
i have created A matrix
A=[1;1];
and b column
b=[1];
then i tried following fun
weighs=fmincon(f(x1,x2),w,A,b)
but it gives me error
Error using optimfcnchk (line 287)
FUN must be a function, a valid string expression, or an inline function
object.
could you help me please what is wrong? thanks in advance

You need to specify the function in fmincon as a function handle or anonymous function; f(x1,x2) evaluates to a scalar double, not a function handle. fmincon will want to evaluate this function with current values of w to check for the quality of the solution, so it needs a way to feed w as an input.
Thus, you need to
Change the function definition to f(w,x1,x2), i.e.
f=#(w,x1,x2) (w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
Write the fmincon call as fmincon(#(u)f(u,x1,x2),...)
However, I would suggest to substitute 1-w(2) for w(1) (or vice versa) in your problem to reformulate it as an unconstrained optimization of one variable (unless w is a real weight, and has to remain between 0 and 1, in which case you still need a constraint).

Related

Integrating a function on matlab

I have a density function f_N which is defined as follows (K_nu(z) is the modified Bessel function):
I want to compute the following integral for each value of N:
The following is the implementation of the above in matlab.
for N=1:100
syms z
f =#(z) (1/(gamma(N)*sqrt(pi))*(z/2).^(N-0.5).*besselk(0.5-N,z));
g = #(z) f(z).*log(f(z));
val=integral(g,0,Inf);
But when I run the above code, it's always returning NaN for varoious values of N with the following warning:
Warning: Infinite or Not-a-Number value encountered
Can someone suggest a simple way to do this or avoid this issue?
I don't think you are doing what you think you are doing. Your declaration of z as a symbol will get overridden by the function handle definition. That means the integral is not a symbolic one, but a numeric one. So what you simply need to do is to drop the function handle notation "#(z)" and do the integral symbolically...
My guess, without thoroughly analysing this, is that one of the points in you integration domain [0,inf] yields a value f (x)=inf, which would destroy a numeric integration technique, but perhaps not a symbolic one.

matlab: using a vector of unknowns in fsolve

I need to solve a system of nonlinear equations; in order to use fsolve , I have written an m-file containing my function "myfun". This function is called by the main m-file.
Both the system and the unknowns must be written using a "for" loop.
Example:
function F=myfun(x)
n=20;`
for j=1:n
c1=sqrt(x(j)^2-3*x(j));
c2=x(j)^(1/2);
F(j)=c1+c2;
end
My problem is that I have to preallocate memory for my vectors, both F and x, otherwise the solver considers numel(x)=1.
But if I declare
F=zeros(n,1);
x=zeros(n,1);
I have the following output:
No solution found.
fsolve stopped because the problem appears regular as measured by the gradient,
but the vector of function values is not near zero as measured by the
default value of the function tolerance.
Any suggestions? Thanks
You don't need the loop, just use
F = sqrt(x.^2-3*x) + x.^(1/2);
Then you also don't need to declare n, c1, c2.
Your error message also doens't sound like it's a problem with the allocation, but more with finding a solution to you fsolve problem.

fit with lsqcurvefit does not work maybe function maldefined

I am trying to fit function F to experimental data.
x_tem and yd are both vectors of size (12,1). The function should find the best
fitting value y_tau of the function to the experimental data.
I just can't find the mistake - matlab is showing me the error :
Error in lsqcurvefit (line 199)
initVals.F = feval(funfcn_x_xdata{3},xCurrent,XDATA,varargin{:});
Caused by:
Failure in initial user-supplied objective function evaluation. LSQCURVEFIT cannot continue.
The code is:
x_tem=Temp_aero_korrektur(:,1);
yd=Temp_aero_korrektur(:,2);
F = #(y_tau,x_tem)((-1)*((273.15-x_tem)*(273.15-y_tau(1))*8.314* (((17.62*x_tem)/(243.12+x_tem))-((17.62*y_tau(1))/(243.12+y_tau(1)))))/(40714.53));
yd_tau = lsqcurvefit(F,-40,x_tem,yd);
There are two possibilities here. One is that you do actually want to use matrix operations in your objective function (so that, for example, x_tem/x_tem gives a single scalar value using mrdivide). If this is the case then you should be calling lsqcurvefit with the transpose of x_tem
yd_tau = lsqcurvefit(F,-40,x_tem',yd);
The other option is that you actually meant to calculate your objective function on each value of x_tem (so, for example, using x_tem./x_tem to give a vector the same length as x_tem). If this is the case then your objective function should be
F = #(y_tau,x_tem)((-1)*((273.15-x_tem).*(273.15-y_tau(1)).*8.314.* (((17.62*x_tem)./(243.12+x_tem))-((17.62*y_tau(1))/(243.12+y_tau(1)))))/(40714.53))
(See documentation for times and rdivide for element-wise operations)

Minimizing a multivariable function

I'm aware of the fminsearch function, but it only seems to be able to solve for one variable.
If my function looks like f(x,y,z) and I want to find the values of x,y,z that gives the lowest result, how would I do this in MatLab? The complexity of f would make it unreasonably difficult to calculate the partial derivatives.
Any help would be appreciated, thanks!
fminsearch is multivariable, for example:
a = fminsearch(#(x)((x(1)-1)^2+(x(2)-2)^2), [0,0]);
the parameter passed to the objective function can be a vector, just be sure to specify the x0 parameter (the second parameter in fminsearch) to the right size.

Integral of a Recursive Function in MATLAB

I want to compute the following symbolic integral which is recursive :
function [y] = myfunc(i,T)
s = sym('s');
x= sym('x');
h=[....] %matrix n*n (function of x)
d=[....] %matrix n*1 (constants)
for k=1:n
if (T>0)
y= int(exp(-s*x)*h(i,k)*myfunc(k,T-x/d(i)),'x',0,T);
end
end
I expected MATLAB, while computing the integral, calls myfunc(k,T-x/d(i)) for different values of 'x' from 0 to T. However, it returns error since myfunc would be called with symbolic value 'x' and not the real value. Indeed, it cannot determine if (T>0) expression is true or false.
I would be thankful if you can suggest how this recursive integral can be computed ?. Thanks
If you want to ensure that a different real value is used in each step of a recursive function, you can define a variable to account for how deep you are.
Suppose we call it depth, and on the top level it is equal to 1. Each time you go one step deeper you increase depth by 1.
Now, if you want to get a number corresponding to the right depth, you can just call it as y(depth).