Matlab Frank Wolfe algorithm for non-linear constraints - matlab

I have a non-linear objective function with non-linear constraints as below:
fun = #(x)x(11)^2 + x(12)^2 + x(13)^2 + x(8)^2 + x(15)^2 + x(16)^2 + x(17)^2 + x(18)^2 +
x(19)^2 + x(20)^2 + x(21)^2 + x(14)^2;
A = [];
b = [];
Aeq = [];
beq = [];
lb = [0,0,0,0,0,0,0,-Inf,0,0,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf,-Inf];
ub = [Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf,Inf];
x0(1:21) = 0;
nonlcon = #consts;
options = optimoptions('fmincon','Display','iter','Algorithm','interior-point');
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options);
function [c,ceq] = consts(x)
c = x(1) + x(2) + x(3) + x(4) + x(5) + x(6) - 1;
ceq(1) = x(7) + x(8) - 0;
ceq(2) = x(5)*x(9) + x(3)*x(10) + x(7) + x(11) - 0;
ceq(3) = x(7) + x(5)*x(9) + x(12) - 0;
ceq(4) = x(7) + x(3)*x(10) + x(13) - 0;
ceq(5) = x(10) + x(14) - 9.666666666666666;
ceq(6) = x(6)*x(9) + x(1)*x(7) + x(10) + x(15) - 17;
ceq(7) = x(10) + x(6)*x(9) + x(16) - 0;
ceq(8) = x(10) + x(1)*x(7) + x(17) - 2.211764705882353;
ceq(9) = x(9) + x(18) - 0;
ceq(10) = x(4)*x(10) + x(2)*x(7) + x(9) + x(19) - 0;
ceq(11) = x(9) + x(4)*x(10) + x(20) - 0;
ceq(12) = x(9) + x(2)*x(7) + x(21) - 0;
end
'fun' is the objective function and 'consts' is the constraints.
I solve my problem with 'interior-point' however, I want to solve this problem with Frank_Wolfe and I cannot find where can I define the constraints.
Based on the documentation:
function [X,fval,i]=frank_wolfe(f,X0,e,A,b,Aeq,beq,lb,ub)
%
% Yinxiao Li
%
% function function [X,fval,i]=frank_wolfe(f,X0,e,A,b,Aeq,beq,lb,ub)
%
% order = 3;
%
% Input: f cost function
% X0 starting feasible point
% e stopping criteria
% A defined in linprog
% b
% Aeq
% beq
% lb
% ub defined in linprog
%
% Output: X optimal point
% fval cost at the optimal point
% i iterations
X=X0;
syms x1 x2 x3 lamida;
df_dx1=diff(f,x1);
df_dx2=diff(f,x2);
df_dx3=diff(f,x3);
x=[100;100;100];
g_f=[100;100;100];
i=0;
while(abs(g_f'*(x-X))>e)%stopping criteria
g_f1=subs(df_dx1,{x1,x2,x3},X);
g_f2=subs(df_dx2,{x1,x2,x3},X);
g_f3=subs(df_dx3,{x1,x2,x3},X);
g_f=[double(g_f1);double(g_f2);double(g_f3)];
[x,feval]=linprog(g_f,A,b,Aeq,beq,lb,ub);
f0=subs(f,{x1,x2,x3},X+lamida*(x-X));
f1=inline(char(f0));
[lamida,fval]=fminbnd(f1,0,1);
X1=X;
X=X+lamida*(x-X);
clear lamida;
syms lamida;
i=i+1;
end
fval=subs(f,{x1,x2,x3},X);
I am not sure:
1- where to define constraints?
2- what should I provide in "linprog" cause as far as I know it is for linear programming.
3- Does Frank wolfe find a global optima or local optima?

Related

Sequential Quadratic Programming Matlab Implementation

I have a problem with my MATLAB code that solves a nonlinear quadratic problem with SQP algorithm (Sequential quadratic programming) but in the "QP-SUB PROBLEM" section of the code that i have formulated analytically a "num2str"error appears and honestly, i don't know how to fix that and also have to tell you that this method uses KT conditions for a better solution .
In every section of the code i write a comment for better understanding and function with constraints can be found in the code below :
% Maximize f(x1,x2) = x1^4 -2x1^2x2 +x1^2 +x1x2^2 -2x1 +4
%
% h1(x1,x2) = x1^2 + x2^2 -2 = 0
% g1(x1,x2) = 0.25x1^2 +0.75x2^2 -1 <=0
% 0 <= x1 <= 4; 0 <= x2 <= 4
%
%--------------------------------------------------------
% The KT conditions for the QP subproblem
% are applied analytically
% There are two cases for a single inequality constraint
% Case (a) : beta = 0 g < 0
% Case (b) : beta ~= 0, g = 0
% The best solution is used
% --------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% management functions
clear % clear all variable/information in the workspace - use CAUTION
clear global % again use caution - clears global information
clc % position the cursor at the top of the screen
close % closes the figure window
format compact % avoid skipping a line when writing to the command window
warning off %#ok<WNOFF> % don't report any warnings like divide by zero etc.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% DATA ---------------------
%%% starting design
xb(1) = 3; xb(2) = 2;
it = 10; % number of iterations
%%% plot range for delx1 : -3 , +3
dx1L = -3; dx1U = +3;
dx2L = -3; dx2U = +3;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Define functions
syms x1 x2 f g h
syms gradf1 gradf2 gradh1 gradh2 gradg1 gradg2
f = x1^4 - 2*x1*x1*x2 + x1*x1 + x1*x2*x2 - 2*x1 + 4;
h = x1*x1 + x2*x2 - 2;
g = 0.25*x1*x1 +0.75*x2*x2 -1;
%%% the gradient functions
gradf1 = diff(f,x1);
gradf2 = diff(f,x2);
% the hessian
hess = [diff(gradf1,x1), diff(gradf1,x2); diff(gradf2,x1), diff(gradf2,x2)];
% gradient of the constraints
gradh1 = diff(h,x1);
gradh2 = diff(h,x2);
gradg1 = diff(g,x1);
gradg2 = diff(g,x2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% graphical/symbolic solution for SLP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('***********************')
fprintf('\nSQP - Example 7.1')
fprintf('\n*********************\n')
for i = 1:it
%figure;
f1 = subs(f,{x1,x2},{xb(1),xb(2)});
g1 = subs(g,{x1,x2},{xb(1),xb(2)});
h1 = subs(h,{x1,x2},{xb(1),xb(2)});
%%% Print Information
fprintf('\n******************************')
fprintf('\nIteration : '),disp(i)
fprintf('******************************\n')
fprintf('Linearized about [x1, x2] : '),disp([xb(1) xb(2)])
fprintf('Objective function value f(x1,x2) : '),disp(f1);
fprintf('Equality constraint value value h(x1,x2) : '),disp(h1);
fprintf('Inequality constraint value value g(x1,x2) : '),disp(g1);
%fprintf('\nsolution for [delx1 delx2] : '),disp(sol')
% hold on
% calculate the value of the gradients
% f1 = subs(f,{x1,x2},{xb(1),xb(2)});
% g1 = subs(g,{x1,x2},{xb(1),xb(2)});
% h1 = subs(h,{x1,x2},{xb(1),xb(2)});
fprintf('\n-----------------------')
fprintf('\nQP - SUB PROBLEM')
fprintf('\n---------------------\n')
gf1 = double(subs(gradf1,{x1,x2},{xb(1),xb(2)}));
gf2 = double(subs(gradf2,{x1,x2},{xb(1),xb(2)}));
hess1 = double(subs(hess,{x1,x2},{xb(1),xb(2)}));
gh1 = double(subs(gradh1,{x1,x2},{xb(1),xb(2)}));
gh2 = double(subs(gradh2,{x1,x2},{xb(1),xb(2)}));
gg1 = double(subs(gradg1,{x1,x2},{xb(1),xb(2)}));
gg2 = double(subs(gradg2,{x1,x2},{xb(1),xb(2)}));
% the QP subproblem
syms dx1 dx2 % change in design
fquad = f1 + [gf1 gf2]*[dx1; dx2] + 0.5*[dx1 dx2]*hess1*[dx1 ;dx2];
hlin = h1 + [gh1 gh2]*[dx1; dx2];
glin = g1 + [gg1 gg2]*[dx1; dx2];
Fquadstr = strcat(num2str(f1),' + ',num2str(gf1), ...
'*','dx1',' + ',num2str(gf2),' * ','dx2', ...
' + 0.5*',num2str(hess1(1,1)),' * dx1^2', ...
' +',num2str(hess1(1,2)),' * dx1*dx2', ...
' + 0.5*',num2str(hess1(2,2)),' * dx2^2');
hlinstr = strcat(num2str(h1),' + ',num2str(gh1), ...
'*','dx1',' + ',num2str(gh2),' * ','dx2');
glinstr = strcat(num2str(g1),' + ',num2str(gg1), ...
'*','dx1',' + ',num2str(gg2),' * ','dx2');
fprintf('Quadratic Objective function f(x1,x2): \n'),disp(Fquadstr);
fprintf('Linearized equality h(x1,x2): '),disp(hlinstr);
fprintf('Linearized inequality g(x1,x2): '),disp(glinstr);
fprintf('\n')
% define Lagrangian for the QP problem
syms lamda beta
F = fquad + lamda*hlin + beta*glin;
fprintf('Case a: beta = 0\n');
Fnobeta = fquad + lamda*hlin;
%%% initialize best solution
dx1best = 0;
dx2best = 0;
Fbbest = 0;
%%%%%%%%%%%%%%%%%%%%%%%
%%% solve case (a) %%%
%%%%%%%%%%%%%%%%%%%%%%%
xcasea = solve(diff(Fnobeta,dx1),diff(Fnobeta,dx2),hlin);
sola = [double(xcasea.dx1) double(xcasea.dx2) double(xcasea.lamda)];
dx1a = double(xcasea.dx1);
dx2a = double(xcasea.dx2);
lamdaa = double(xcasea.lamda);
hlina = double(subs(hlin,{dx1,dx2},{dx1a,dx2a}));
glina = double(subs(glin,{dx1,dx2},{dx1a,dx2a}));
Fa = double(subs(Fnobeta,{dx1,dx2,lamda},{dx1a,dx2a,lamdaa}));
%%% results for case (a)
x1a = dx1a + xb(1);
x2a = dx2a + xb(2);
fv = double(subs(f,{x1,x2},{x1a,x2a}));
hv = double(subs(h,{x1,x2},{x1a,x2a}));
gv = double(subs(g,{x1,x2},{x1a,x2a}));
fprintf('Change in design vector: '),disp([dx1a dx2a]);
fprintf('The linearized quality constraint: '),disp(hlina);
fprintf('The linearized inequality constraint: '),disp(glina);
fprintf('New design vector: '),disp([x1a x2a]);
fprintf('The objective function: '),disp(fv);
fprintf('The equality constraint: '),disp(hv);
fprintf('The inequality constraint: '),disp(gv);
if (glina <= 0)
xb(1) = xb(1) + dx1a;
xb(2) = xb(2) + dx2a;
fbest = Fa;
dx1best = dx1a;
dx2best = dx2a;
end
%%%%%%%%%%%%%%%%%%%%%%%
%%% solve case (b) %%%
%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n Case b: g = 0\n');
xcaseb = solve(diff(F,dx1),diff(F,dx2),hlin,glin);
solb = [double(xcaseb.dx1) double(xcaseb.dx2) double(xcaseb.lamda) double(xcaseb.beta)];
dx1b = double(xcaseb.dx1);
dx2b = double(xcaseb.dx2);
betab = double(xcaseb.beta);
lamdab = double(xcaseb.lamda);
hlinb = double(subs(hlin,{dx1,dx2},{dx1b,dx2b}));
glinb = double(subs(glin,{dx1,dx2},{dx1b,dx2b}));
Fb = double(subs(F,{dx1,dx2,lamda,beta},{dx1b,dx2b,lamdab,betab}));
x1b = dx1b + xb(1);
x2b = dx2b + xb(2);
fv = double(subs(f,{x1,x2},{x1b,x2b}));
hv = double(subs(h,{x1,x2},{x1b,x2b}));
gv = double(subs(g,{x1,x2},{x1b,x2b}));
fprintf('Change in design vector: '),disp([dx1b dx2b]);
fprintf('The linearized quality constraint: '),disp(hlinb);
fprintf('The linearized inequality constraint: '),disp(glinb);
fprintf('New design vector: '),disp([x1b x2b]);
fprintf('The objective function: '),disp(fv);
fprintf('The equality constraint: '),disp(hv);
fprintf('The inequality constraint: '),disp(gv);
fprintf('Multiplier beta: '),disp(betab);
fprintf('Multiplier lamda: '),disp(lamdab);
if (betab > 0) & (Fb <= fbest)
xb(1) = x1b;
xb(2) = x2b;
dx1best = dx1b;
dx2best = dx2b;
end
%%% stopping criteria
if ([dx1best dx2best]*[dx1best dx2best]') <= 1.0e-08
fprintf('\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
fprintf('\nStopped: Design Not Changing')
fprintf('\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n\n')
break;
elseif i == it
fprintf('\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
fprintf('\nStpped: Number of iterations at maximum')
fprintf('\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n\n')
break;
end
end
f1, g1, h1 are still syms variable type.
Change them to numeric type using the function double() before applying
the function num2str()
You have already applied double() to the variables
gf1, gf2, gh1, gh2,gg1, gg2 and hess1
right above, no need to touch them
Here is the section you should replace
Fquadstr = strcat(num2str(f1),' + ',num2str(gf1), ...
'*','dx1',' + ',num2str(gf2),' * ','dx2', ...
' + 0.5*',num2str(hess1(1,1)),' * dx1^2', ...
' +',num2str(hess1(1,2)),' * dx1*dx2', ...
' + 0.5*',num2str(hess1(2,2)),' * dx2^2');
hlinstr = strcat(num2str(h1),' + ',num2str(gh1), ...
'*','dx1',' + ',num2str(gh2),' * ','dx2');
glinstr = strcat(num2str(g1),' + ',num2str(gg1), ...
'*','dx1',' + ',num2str(gg2),' * ','dx2');
by this
% apply double() to f1
Fquadstr = strcat(num2str(double(f1)),' + ',num2str(gf1), ...
'*','dx1',' + ',num2str(gf2),' * ','dx2', ...
' + 0.5*',num2str(hess1(1,1)),' * dx1^2', ...
' +',num2str(hess1(1,2)),' * dx1*dx2', ...
' + 0.5*',num2str(hess1(2,2)),' * dx2^2');
% apply double() to h1
hlinstr = strcat(num2str(double(h1)),' + ',num2str(gh1), ...
'*','dx1',' + ',num2str(gh2),' * ','dx2');
% apply double() to g1
glinstr = strcat(num2str(double(g1)),' + ',num2str(gg1), ...
'*','dx1',' + ',num2str(gg2),' * ','dx2');

Matlab: Nonlinear equation solver

How do I solve these sets of equations and can matlab find a solution? I'm solving for x1,x2,x3,x4,c1,c2,c3,c4.
syms c1 c2 c3 c4 x1 x2 x3 x4;
eqn1 = c1 + c2 + c3 + c4 == 2;
eqn2 = c1*x1 + c2*x2 + c3*x3 + c4*x4 == 0;
eqn3 = c1*x1^2 + c2*x2^2 + c3*x3^2 + c4*x4^2 == 2/3;
eqn4 = c1*x1^3 + c2*x2^3 + c3*x3^3 + c4*x4^3 == 0;
eqn5 = c1*x1^4 + c2*x2^4 + c3*x3^4 + c4*x4^4 == 2/5;
eqn6 = c1*x1^5 + c2*x2^5 + c3*x3^5 + c4*x4^5 == 0;
eqn7 = c1*x1^6 + c2*x2^6 + c3*x3^6 + c4*x4^6 == 2/7;
eqn8 = c1*x1^7 + c2*x2^7 + c3*x3^7 + c4*x4^7 == 0;
From what I understand, matlab has fsolve, solve, and linsolve, but I'm uncertain how to use them.
You have a system of non-linear equations, so you can use fsolve to find a solution.
First of all you need to create a function, say fcn, of a variable x, where x is a vector with your initial point. The function defines an output vector, depending on the current vector x.
You have eight variables, so your vector x will consist of eight elements. Let's rename your variables in this way:
%x1 x(1) %c1 x(5)
%x2 x(2) %c2 x(6)
%x3 x(3) %c3 x(7)
%x4 x(4) %c4 x(8)
Your function will look like this:
function F = fcn(x)
F=[x(5) + x(6) + x(7) + x(8) - 2 ;
x(5)*x(1) + x(6)*x(2) + x(7)*x(3) + x(8)*x(4) ;
x(5)*x(1)^2 + x(6)*x(2)^2 + x(7)*x(3)^2 + x(8)*x(4)^2 - 2/3 ;
x(5)*x(1)^3 + x(6)*x(2)^3 + x(7)*x(3)^3 + x(8)*x(4)^3 ;
x(5)*x(1)^4 + x(6)*x(2)^4 + x(7)*x(3)^4 + x(8)*x(4)^4 - 2/5 ;
x(5)*x(1)^5 + x(6)*x(2)^5 + x(7)*x(3)^5 + x(8)*x(4)^5 ;
x(5)*x(1)^6 + x(6)*x(2)^6 + x(7)*x(3)^6 + x(8)*x(4)^6 - 2/7 ;
x(5)*x(1)^7 + x(6)*x(2)^7 + x(7)*x(3)^7 + x(8)*x(4)^7
];
end
You can evaluate your function with some initial value of x:
x0 = [1; 1; 1; 1; 1; 1; 1; 1];
F0 = fcn(x0);
Using x0 as initial point your function returns:
F0 =
2.0000
4.0000
3.3333
4.0000
3.6000
4.0000
3.7143
4.0000
Now you can start fsolve which will try to find some vector x, such as your function returns all zeros:
[x,fval]=fsolve(#fcn, x0);
You will get something like this:
x =
0.7224
0.7224
-0.1100
-0.7589
0.3599
0.3599
0.6794
0.5768
fval =
-0.0240
0.0075
0.0493
0.0183
-0.0126
-0.0036
-0.0733
-0.0097
As you can see, the function values are really close to zeros, but you probably noticed that the optimization algorithm was stopped because of the limited count of the function evaluation steps stored in options.MaxFunEvals (by default 800). Another possible reason is the limited number of iterations stored in MaxIter (by default 400).
Redefine these value using the parameter options:
options = optimset('MaxFunEvals',2000, 'MaxIter', 1000);
[x,fval]=fsolve(#fcn, x0, options);
Now your output is much better:
x =
0.7963
0.7963
-0.0049
-0.7987
0.2619
0.2619
0.9592
0.5165
fval =
-0.0005
-0.0000
-0.0050
0.0014
0.0208
-0.0001
-0.0181
-0.0007
Just play with different parameter values, in order to achieve a tolerable precision level for your problem.

Matlab: Nonlinear equation Optimization

This question is related to the post below:
Matlab: Nonlinear equation solver
With 8 variables x0-x8, I got great results. However, when I increase to solving 10 variables, the results aren't so good. Even if my "guess" is close to the actual value and change the max iteration to 100000, the results are still poor. Is there anything else I can do?
Here is the code:
function F = fcn(x)
F=[x(6) + x(7) + x(8) + x(9) + x(10)-2 ;
x(6)*x(1) + x(7)*x(2) + x(8)*x(3) + x(9)*x(4) + x(10)*x(5) ;
x(6)*x(1)^2 + x(7)*x(2)^2 + x(8)*x(3)^2 + x(9)*x(4)^2 + x(10)*x(5)-2/3 ;
x(6)*x(1)^3 + x(7)*x(2)^3 + x(8)*x(3)^3 + x(9)*x(4)^3 + x(10)*x(5) ;
x(6)*x(1)^4 + x(7)*x(2)^4 + x(8)*x(3)^4 + x(9)*x(4)^4 + x(10)*x(5)-2/5 ;
x(6)*x(1)^5 + x(7)*x(2)^5 + x(8)*x(3)^5 + x(9)*x(4)^5 + x(10)*x(5) ;
x(6)*x(1)^6 + x(7)*x(2)^6 + x(8)*x(3)^6 + x(9)*x(4)^6 + x(10)*x(5)-2/7 ;
x(6)*x(1)^7 + x(7)*x(2)^7 + x(8)*x(3)^7 + x(9)*x(4)^7 + x(10)*x(5) ;
x(6)*x(1)^8 + x(7)*x(2)^8 + x(8)*x(3)^8 + x(9)*x(4)^8 + x(10)*x(5)-2/9 ;
x(6)*x(1)^9 + x(7)*x(2)^9 + x(8)*x(3)^9 + x(9)*x(4)^9 + x(10)*x(5)
];
end
clc
clear all;
format long
x0 = [0.90; 0.53; 0; -0.53; -0.90; 0.23; 0.47; 0.56; 0.47; 0.23]; %Guess
F0 = fcn(x0);
[x,fval]=fsolve(#fcn, x0) %solve without optimization
options = optimset('MaxFunEvals',100000, 'MaxIter', 100000); %optimization criteria
[x,fval]=fsolve(#fcn, x0, options) %solve with optimization
Here are the actual values I'm trying to get:
x1 = 0.906179
x2 = 0.538469
x3 = 0.000000
x4 = -0.53846
x5 = -0.906179
x6 = 0.236926
x7 = 0.478628
x8 = 0.568888
x9 = 0.478628
x10 = 0.236926
The result of such optimization functions like fsolve depends on the initial point very much. A non-linear function like yours can have a lot of local minima and your option is to randomly dice the initial point and hope it will lead the optimization to a better minimum than before.
You can do like this:
clear;
options = optimset('MaxFunEvals',2000, 'MaxIter', 1000, 'Display', 'off');
n = 200; %how many times calculate f with different initial points
z_min = 10000; %the current minimum Euclidian distance between fval and zeros
for i=1:n
x0 = rand(10, 1);
[x,fval]=fsolve(#fcn, x0, options);
z = norm(fval);
if (z < z_min)
z_min = z;
x_best = x;
f_best = fval;
display(['i = ', num2str(i), '; z_min = ', num2str(z_min)]);
display(['x = ', num2str(x_best')]);
display(['f = ', num2str(f_best')]);
fprintf('\n')
end
end
Change the maximum number of the optimization loops and look at the z value. It shows how close your function is to a zero vector.
The best solution I've got so far:
x_best =
0.9062
-0.9062
-0.5385
0.5385
0.0000
0.2369
0.2369
0.4786
0.4786
0.5689
f_best =
1.0e-08 * %these are very small numbers :)
0
0.9722
0.9170
0.8740
0.8416
0.8183
0.8025
0.7929
0.7883
0.7878
For this solution z_min is 2.5382e-08.

Matrix calculation gets slower after each iteration in matlab

I have a 1024*1024*51 matrix. I'll do calculations to change some value of the matrix within for loops (change the value of matrix for each iteration). I find that the computing speed gets slower and slower and finally my computer gets into trouble.However the size of the matrix doesn't change. Anyone can shed some light on this problem?
function ActiveContours3D(method,grad,im,mu,nu,lambda1,lambda2,TimeSteps)
epsilon = 10e-10;
tic
fid=fopen('Chr18_z_25of25tiles-C=0_c0_n000.raw','rb','ieee-le');
Xdim = 1024;
Ydim = 1024;
Zdim = 51;
A = fread(fid,[Xdim Ydim*Zdim],'int16');
A = double(A);
size_of_A = size(A)
for(i=1:Zdim)
u0_color(:,:,i) = A(1 : Xdim , (i-1)*Ydim+1 : i*Ydim);
end
fclose(fid)
time = toc
[M,N,P,color] = size(u0_color);
size(u0_color );
u0_color = double(u0_color); % Convert u0_color values to double;
u0 = u0_color(:,:,:,1); % Define the Grayscale volumetric image.
u0_color = uint8(u0_color); % Necessary for color visualization
x = 1:M;
y = 1:N;
z = 1:P;
dx = 1
dy = 1
dz = 1
dim_approx = 2*M*N*P / sqrt(M*N*P);
if(method == 'Explicit')
dt = 0.9 / ((2*mu/(dx^2)) + (2*mu/(dy^2)) + (2*mu/(dz^2))) % 90% CFL
elseif(method == 'Implicit')
dt = (10e7) * 0.9 / ((2*mu/(dx^2)) + (2*mu/(dy^2)) + (2*mu/(dz^2)))
end
[X,Y,Z] = meshgrid(x,y,z);
x0 = (M+1)/2;
y0 = (N+1)/2;
z0 = (P+1)/2;
r0 = min(min(M,N),P)/3;
phi = sqrt((X-x0).^2 + (Y-y0).^2 + (Z-z0).^2) - r0;
phi_visualize = phi; % Use this for visualization in 3D
phi = permute(phi,[2,1,3]); % Use this for computations in 3D
write_to_binary_file(phi_visualize,0); % record initial conditions
tic
for(n=1:TimeSteps)
n
c1 = C1_3d(u0,phi);
c2 = C2_3d(u0,phi);
% x
phi_xp = [phi(2:M,:,:); phi(M,:,:)]; % vertical concatenation
phi_xm = [phi(1,:,:); phi(1:M-1,:,:)]; % (since x values are rows)
% cat(1,A,B) is the same as [A;B]
Dx_m = (phi - phi_xm)/dx; % first derivatives
Dx_p = (phi_xp - phi)/dx;
Dxx = (Dx_p - Dx_m)/dx; % second derivative
% y
phi_yp = [phi(:,2:N,:) phi(:,N,:)]; % horizontal concatenation
phi_ym = [phi(:,1,:) phi(:,1:N-1,:)]; % (since y values are columns)
% cat(2,A,B) is the same as [A,B]
Dy_m = (phi - phi_ym)/dy;
Dy_p = (phi_yp - phi)/dy;
Dyy = (Dy_p - Dy_m)/dy;
% z
phi_zp = cat(3,phi(:,:,2:P),phi(:,:,P));
phi_zm = cat(3,phi(:,:,1) ,phi(:,:,1:P-1));
Dz_m = (phi - phi_zm)/dz;
Dz_p = (phi_zp - phi)/dz;
Dzz = (Dz_p - Dz_m)/dz;
% x,y,z
Dx_0 = (phi_xp - phi_xm) / (2*dx);
Dy_0 = (phi_yp - phi_ym) / (2*dy);
Dz_0 = (phi_zp - phi_zm) / (2*dz);
phi_xp_yp = [phi_xp(:,2:N,:) phi_xp(:,N,:)];
phi_xp_ym = [phi_xp(:,1,:) phi_xp(:,1:N-1,:)];
phi_xm_yp = [phi_xm(:,2:N,:) phi_xm(:,N,:)];
phi_xm_ym = [phi_xm(:,1,:) phi_xm(:,1:N-1,:)];
phi_xp_zp = cat(3,phi_xp(:,:,2:P),phi_xp(:,:,P));
phi_xp_zm = cat(3,phi_xp(:,:,1) ,phi_xp(:,:,1:P-1));
phi_xm_zp = cat(3,phi_xm(:,:,2:P),phi_xm(:,:,P));
phi_xm_zm = cat(3,phi_xm(:,:,1) ,phi_xm(:,:,1:P-1));
phi_yp_zp = cat(3,phi_yp(:,:,2:P),phi_yp(:,:,P));
phi_yp_zm = cat(3,phi_yp(:,:,1) ,phi_yp(:,:,1:P-1));
phi_ym_zp = cat(3,phi_ym(:,:,2:P),phi_ym(:,:,P));
phi_ym_zm = cat(3,phi_ym(:,:,1) ,phi_ym(:,:,1:P-1));
if(grad == 'Dirac')
Grad = DiracDelta(phi); % Dirac delta
%Grad = 1;
elseif(grad == 'Grad ')
Grad = (((Dx_0.^2)+(Dy_0.^2)+(Dz_0.^2)).^(1/2)); % |grad phi|
end
if(method == 'Explicit')
% CURVATURE: *mu*k|grad phi|* (central differences):
K = zeros(M,N,P);
Dxy = (phi_xp_yp - phi_xp_ym - phi_xm_yp + phi_xm_ym) / (4*dx*dy);
Dxz = (phi_xp_zp - phi_xp_zm - phi_xm_zp + phi_xm_zm) / (4*dx*dz);
Dyz = (phi_yp_zp - phi_yp_zm - phi_ym_zp + phi_ym_zm) / (4*dy*dz);
K = ( (Dx_0.^2).*Dyy - 2*Dx_0.*Dy_0.*Dxy + (Dy_0.^2).*Dxx ...
+ (Dx_0.^2).*Dzz - 2*Dx_0.*Dz_0.*Dxz + (Dz_0.^2).*Dxx ...
+ (Dy_0.^2).*Dzz - 2*Dy_0.*Dz_0.*Dyz + (Dz_0.^2).*Dyy) ./ ((Dx_0.^2 + Dy_0.^2 + Dz_0.^2).^(3/2) + epsilon);
phi_temp = phi + dt * Grad .* ( mu.*K + lambda1*(u0 - c1).^2 - lambda2*(u0 - c2).^2 );
elseif(method == 'Implicit')
C1x = 1 ./ sqrt(Dx_p.^2 + Dy_0.^2 + Dz_0.^2 + (10e-7)^2);
C2x = 1 ./ sqrt(Dx_m.^2 + Dy_0.^2 + Dz_0.^2 + (10e-7)^2);
C3y = 1 ./ sqrt(Dx_0.^2 + Dy_p.^2 + Dz_0.^2 + (10e-7)^2);
C4y = 1 ./ sqrt(Dx_0.^2 + Dy_m.^2 + Dz_0.^2 + (10e-7)^2);
C5z = 1 ./ sqrt(Dx_0.^2 + Dy_0.^2 + Dz_p.^2 + (10e-7)^2);
C6z = 1 ./ sqrt(Dx_0.^2 + Dy_0.^2 + Dz_m.^2 + (10e-7)^2);
% m = (dt/(dx*dy)) * Grad .* mu; % 2D
m = (dt/(dx*dy)) * Grad .* mu;
C = 1 + m.*(C1x + C2x + C3y + C4y + C5z + C6z);
C1x_2x = C1x.*phi_xp + C2x.*phi_xm;
C3y_4y = C3y.*phi_yp + C4y.*phi_ym;
C5z_6z = C5z.*phi_zp + C6z.*phi_zm;
phi_temp = (1 ./ C) .* ( phi + m.*(C1x_2x+C3y_4y) + (dt*Grad).*(lambda1*(u0 - c1).^2) - (dt*Grad).*(lambda2*(u0 - c2).^2) );
end
phi = phi_temp;
phi_visualize = permute(phi,[2,1,3]);
write_to_binary_file(phi_visualize,n); % record
end
time = toc
n = n
T = dt*n
clear
clear all
In general Matlab keeps track of all the variables in the form of matrix. When you work with lot of variables with many dimensions the RAM memory will be allocated for storing this variable. Hence on working with lots of variables that is gonna run for multiple iterations it is better to clear the variable from the memory. To do so use the command
clear variable_name_1, variable_name_2,... variable_name_3;
Although keeping all the variables keeps the code to look organised, however when you face such issues try clearing the unwanted variables.
Check this link to use clear command in detail: http://www.mathworks.in/help/matlab/ref/clear.html

MATLAB's 'solve,' applied to a system of equations, gives me a solution that doesn't satisfy one of the equations

I'm using the MATLAB function 'solve' to solve a system of six equations and six variables. In the solution it gives, at least one of the equations seems not to be satisfied. Here's my code for the problem:
% given parameters
alpha = .05; % exogenous rate of cost reductions
sigma = .05; % exogenous uncertainty (infinitessimal st dev)
p0 = 10; % initial carbon price
p1 = 50; % carbon price under policy
lambda_p = .05; % Poisson arrival rate of policy
lambda_q = .01; % Probability of reversion to no policy state
r = .03; % discount rate
% exponents for solution
beta1 = (.5*sigma^2 + alpha + sqrt((.5*sigma^2 + alpha)^2 + 2*sigma^2*(r+lambda_p)))/sigma^2;
beta2 = (.5*sigma^2 + alpha - sqrt((.5*sigma^2 + alpha)^2 + 2*sigma^2*(r+lambda_p)))/sigma^2;
beta3 = (.5*sigma^2 + alpha - sqrt((.5*sigma^2 + alpha)^2 + 2*sigma^2*r))/sigma^2;
beta4 = (.5*sigma^2 + alpha - sqrt((.5*sigma^2 + alpha)^2 + 2*sigma^2*(r+lambda_p+lambda_q)))/sigma^2;
syms a0 a1 ka ks B1 B2
S = solve(p1 - a1 == (lambda_p*lambda_q*ka*a1^beta3 + lambda_q*ks*a1^beta4)/(lambda_p + lambda_q), ...
-1 == (lambda_p*lambda_q*ka*beta3*a1^(beta3-1) + lambda_q*ks*beta4*a1^(beta4-1))/(lambda_p + lambda_q), ...
p0 - a0 == B1*a0^beta1 + B2*a0^beta2 - lambda_p*a0/(alpha+lambda_p+r) + lambda_p*p1/(r+lambda_p), ...
-1 == B1*beta1*a0^(beta1-1) + B2*beta2*a0^(beta2-1) - lambda_p/(alpha+lambda_p+r), ...
(lambda_p*lambda_q*ka*a1^beta3 - lambda_p*ks*a1^beta4)/(lambda_p + lambda_q) == B1*a1^beta1 + B2*a1^beta2 - lambda_p*a1/(alpha+lambda_p+r) + lambda_p*p1/(r+lambda_p), ...
(lambda_p*lambda_q*ka*beta3*a1^(beta3-1) - lambda_p*ks*beta4*a1^(beta4-1))/(lambda_p + lambda_q) == B1*beta1*a1^(beta1-1) + B2*beta2*a1^(beta2-1) - lambda_p/(alpha+lambda_p+r));
The third equation isn't satisfied. When I obtain the output S, I calculate
>> p0-S.a0
ans =
-51.139888401602841212761952348352
and
>> S.B1*S.a0^beta1 + S.B2*S.a0^beta2 - lambda_p*S.a0/(alpha+lambda_p+r) + lambda_p*p1/(r+lambda_p)
ans =
4.58887467530944339251344448794
which aren't equal. Any ideas as to what's wrong? Thanks.