Index Exceeds Array Bounds
Show older comments
I keep getting an "Index exceeds array bounds" message with the code below. I am running it as seen in the picture where the objective function and constraint functions have their own editor window and then the lifecycle code is pasted into the command window. Any idea what may be causing this?
function y=Lifecycle_Objfun(x,beta,T)
% variables: c(1),c(2),...,c(100), I(1),I(2),...,I(100)
y=sum((beta.^(0:(T-1))') .* ((c(1:100)^(1-gam))/(1-gam)));
y=-y;
end
function [cineq,ceq]=Lifecycle_ConFun(x,T,Q,A,a,initI,termI)
% variables: c(1),c(2),...,c(100), I(1),I(2),...,I(100)
cineq = [];
ceq = zeros(T+2,1);
c = x(1:T);
I = x((T+1):(2*T+1));
% transition law for I
for i=1:100
ceq(i) = I(i) - ((A(i)*Q(i)^a-c(i));
end
% initial saving
ceq(T+1) = I(1) - initI;
% terminal saving
ceq(T+2) = I(100) - termI;
end
function lifecycle()
beta=0.96;
d=0.1;
a=0.33;
phi=0.975;
gam=2;
Iss=0.3533;
Q(1)=1;
initI=0;
termI=0;
Q(T+1)=(1-d)*Q(T)+I(T);
phi*Iss=I(T);
T=(1:100);
-c(T)=0
-Q(T)=0
% variables: c(1),c(2),...,c(100), I(1),I(2),...,I(100)
x0 = ones(2*T+1,1);
lb = zeros(2*T+1,1);
lb(1:T) = 0.01;
xsol = fmincon(@(x) Lifecycle_Objfun(x,beta,T),x0,[],[],[],[],lb,[],...
@(x) Lifecycle_ConFun(x,T,Q,A,a,initI,termI));
c = xsol(1:T);
I = xsol((T+1):(2*T+1));
times=(1:T)';
figure
plot(times,c,'k-',[times;T+1],I,'b-','LineWidth',2)
legend('consumption','savings','Location','NorthWest');
xlabel('Time')
title('Optimal Solution of Life Cycle Problem')
set(gca,'fontsize',16)
xlim([1 T+1])
ylim([0 14])
options = optimoptions('fmincon','MaxFunctionEvaluations',100000);
xsol = fmincon(@(x) Lifecycle_Objfun(x,beta,T),x0,[],[],[],[],lb,[],...
@(x) Lifecycle_ConFun(x,T,Q,A,a,initI,termI),options);
c = xsol(1:T);
I = xsol((T+1):(2*T+1));
figure
plot(times,c,'k-',[times;T+1],I,'b-','LineWidth',2)
legend('consumption','savings','Location','NorthWest');
xlabel('Time')
title('Optimal Solution of Life Cycle Problem')
set(gca,'fontsize',16)
xlim([1 T+1])
ylim([0 14])
end
Answers (1)
Walter Roberson
on 27 Apr 2018
You have
phi*Iss=I(T);
-c(T)=0
-Q(T)=0
It is not valid to have any operation other than indexing calculations on the left side of the "="
If you are trying to make statements of functional relationship, expression an equation such as
phi*Iss = (something)
then you cannot do that in that form. The closest you would be able to get to that would be to use the symbolic toolbox and use
eqn = phi*Iss == something
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!