MATLAB errors when using Lagrange Multipliers? - matlab

I have code that, when run, should correctly use Lagrange Multipliers to find the maximum/minimum of a function here:
clear all
syms x y L;
f = x^4+2*y^4;
g = x^2+5*y^2+2*y^2-10;
firstpart=jacobian(f,[x y])-L*jacobian(g,[x y]);
[Lsoln,xsoln,ysoln]=solve(firstpart,x^2+5*y^2+2*y^2-10);
subs(f,{x,y},{xsoln,ysoln})
% The coordinates that correspond with the greatest and smallest values
% above are the maximum and minimum, respectively.
However, when I run it, I get four errors:
Error using sym.getEqnsVars>checkVariables (line 92) The second
argument must be a vector of symbolic variables.
Error in sym.getEqnsVars (line 62)
checkVariables(vars);
Error in solve>getEqns (line 450) [eqns, vars] =
sym.getEqnsVars(argv{:});
Error in solve (line 225) [eqns,vars,options] = getEqns(varargin{:});
Could anyone help?

You are passing two equations as individual arguments zu solve, that is not possible. You have to put both into an array
[Lsoln,xsoln,ysoln]=solve([firstpart,x^2+5*y^2+2*y^2-10] );

Related

How do I use fplot for a function with a variable and a parameter?

I'm trying to plot a function that is in a separate .m file:
function V = Vitesse_Glissade(x, Courbe)
%some code
end
x is a variable evaluated between 0 and 25, but Courbe is a 4th order polinomial in the form of a vector that the function uses.
I have tried this but it doesn't work:
figure
fplot(#(x) 'Vitesse_Glissade',[0 25], Courbe);
I get this error message:
Error using /
Matrix dimensions must agree.
Error in fplot (line 96)
maxstep = (xmax - xmin) / N;
Error in Glissage (line 37)
fplot(#(x) 'Vitesse_Glissade',[0 25], Courbe);
I have looked at posts where for multiple variable input in fplot, but since I use a vector as a parameter, it's different.
Thanks in advance!
This is not how function handles work. Use this syntax instead:
fplot(#(x)Vitesse_Glissade(x,Courbe),[0 25]);

2D fused Lasso with Matlab CVX

I wrote a 2D fused lasso code here.
[m n] = size(circle);
cvx_begin
variable theta(m, n);
minimize( norm(circle-theta, 'fro'));
subject to
sum(sum(abs(theta(:,1:n-1)-theta(:,2:n)))) == 0;
sum(sum(abs(theta(1:m-1,:)-theta(2:m,:)))) == 0;
cvx_end
Weirdly, the program report,
In cvxprob (line 28) In cvx_begin (line 41) Error using cvxprob/newcnstr (line 192) Disciplined convex programming error:
Invalid constraint: {convex} == {constant}
Error in == (line 12) b = newcnstr( evalin( 'caller', 'cvx_problem',
'[]' ), x, y, '==' );
After I remove abs() in the constraint, the program could run, but that's not what constraints I expect to be.
I think you can try stacking the matrices into vectors, then use L1 norm. In CVX, it's just norm(variable, 1). It will do the same as you wrote here: sum of absolute elementary-wise differences.

Error: A and B must be floating point scalars

I am trying to optimize the function using fminsearch and function handle
but, I get the error A and B must be floating point scalars. In detalis,
Error using integral (line 86)
A and B must be floating point scalars.
Error in #(x,p)(integral(#(n)((p(1)-p(2))*exp(n)),-inf,x+3))
Error in #(x)((x-f2(x,p)).^2)
Error in integralCalc/iterateScalarValued (line 314)
fx = FUN(t);
Error in integralCalc/vadapt (line 133)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen);
Error in integralCalc (line 76)
[q,errbnd] = vadapt(#AtoBInvTransform,interval);
Error in integral (line 89)
Q = integralCalc(fun,a,b,opstruct);
Error in #(p)(integral(#(x)((x-f2(x,p)).^2),-3,3))
Error in fminsearch (line 191)
fv(:,1) = funfcn(x,varargin{:});
How can I solve this?
i think x-3 become a problem but i cannot deal with it.
x should be variable in f2 in order to do integral with respect to x in q3
Thank you in advance
sigma=0.1;
f2=#(x,p)(integral(#(n)((p(1)-p(2))*exp(n)),-inf,x+3));
q3=#(p)(integral(#(x)((x-f2(x,p)).^2),-3,3));
[p, fval] = fminsearch(q3,[0.1 0.4]);
The problem is that when you integrate over x, the function "integrate" gives f2 a vector to evaluate. Which is the same reason you use the dot notation in the function "q3".
The quick fix is to use arrayfun around the "f2" - but you should really consider to adapt to what user20160 suggested in the comments, namely to make full functions, then it will be easier to debug and as it takes in a vector, you can make a for loop, which runs over the inputted endpoints. Standard for-loops are faster than standard arrayfun.

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

Using fgoalattain() or solve() for Matlab

I am trying to solve a problem (think excel "goal seek") where given a specific rate of return, matlab can solve for the variable "y" (which is used to multiply a matrix).
I've tried using fgoalattain (i don't understand it) and solve
here is the function which basically adds some arrays together to make a cashflow with y being a double. ppam_gen is a n*1 matrix. other_tot is a n*1 matrix.
down_pmt is a double.
function ansirr = cirr(y)
cf_gen_oth = y*ppam_gen + oth_tot
dp = [-down_pmt]
cashflow = [dp;cf_gen_oth]
ansirr = irr(cashflow)
%ansirr = irr([dp; y*ppam_gen + oth_tot])
end
x = fgoalattain(#cirr,0.001,.15,abs(.15))
does not work, the following error is given:
Error using roots (line 28)
Input to ROOTS must not contain NaN or Inf.
Error in irr (line 134)
coeff = roots(fliplr(cf(:,loop)')); % Find roots of polynomial
Error in ppa_model/cirr (line 139)
ansirr = irr(cashflow)
Error in goalcon (line 26)
f = feval(funfcn{3},x,varargin{:});
Error in
fgoalattain>#(y,varargin)feval(cfun{3},y,neqgoals,funfcn,confcn,WEIGHT,GOAL,x,errCheck,varargin{:})
(line 473)
cfun{3} = #(y,varargin)
feval(cfun{3},y,neqgoals,funfcn,confcn,WEIGHT,GOAL,x,errCheck,varargin{:});
Error in nlconst (line 746)
[nctmp,nceqtmp] = feval(confcn{3},x,varargin{:});
Error in fgoalattain (line 519)
[xnew,ATTAINFACTOR,LAMBDA,EXITFLAG,OUTPUT]=...
Error in ppa_model (line 152)
r = fgoalattain(#cirr,0.001,.15,abs(.15))
and using symbolic toolbox doesn't work either.
syms y
solve(irr([-down_pmt ; y*ppam_gen + oth_tot]) == 0.15)
throws the error:
Error using assignin
Attempt to add "y" to a static workspace.
See MATLAB Programming, Restrictions on Assigning to Variables for details.
Error in syms (line 66)
assignin('caller',x,sym(x));
Error in ppa_model (line 152)
syms y