- You need to define either 1 value (1x1) for d or 7 values (1x7 i.e.equal to you for loop iteration) and index it with each iteration like you are indexing w(t).
- use if else instead of for d=0 & d=1 i.e
How to code when a variable has been vectorized and has different values in a for loop
1 view (last 30 days)
Show older comments
I would like to code the earnings of a household which consists of a retired parent and a child. The parent faces health and survival risk. Parent receives social security payment SS if alive. If parent is not healthy, the child needs to take care of the parent. There is a time cost xi if the parent is not healthy since when taking care of the parent, the child cannot work. Assume the household lives for 7 periods, and the probability of being alive and healthy is different in each period. The code is something as follows
%setup
d=[0;1];%d=0 parent has died, d=1 parent is alive
h=[0;1]; %h=0 parent is health, h=1 parent needs long-term care
A=(0:0.05:100)'; %grid of asset which is used for a follow-up anaysis not relevant for this question
Nd_grid=length(d);
Nh_grid=length(h);
N_grid =length(A);
Aind = 1:N_grid;
Hind=1:Nh_grid;
Dind=1:Nd_grid;
[AIND,HIND,DIND] = ndgrid(Aind,Hind,Dind);
%code for household earnings
e=zeros(N_grid*Nh_grid*Nd_grid,1);
for t=1:7
e(:,t)=w(t).*(1-xi.*h(HIND(:))).*(1-tau_l-tau_ss)+d(DIND(:)).*SS; %w is the wage rate at time t, xi is the time cost of taking care of the parent,tau_l and tau_ss are the taxes
end
My question is , when parent dies, there will be no time cost for taking care of the parent. But this cannot be done by my code above. I tried to code as follows, but it returns an error of "Index exceeds the number of array elements (1)." I think this is because I have vectorized d, so the dimension is different, but I don't know how I should code. Thank you!
for t=1:7
for d=0
e(:,t)=w(t)*(1-tau_l-tau_ss)+d(DIND(:)).*(0.3*SS); %w is the wage rate, when d=0 parent has died so no care cost for the child
end
for d=1
e(:,t)=w(t).*(1-xi.*h(HIND(:))).*(1-tau_l-tau_ss)+d(DIND(:)).*SS; %xi is the time cost of taking care of the parent
end
end
0 Comments
Accepted Answer
Mehmed Saad
on 18 May 2020
Edited: Mehmed Saad
on 18 May 2020
(if d==0) %for vecotr d of size equal to for loop iterations put if(d(t)==0)
% % do this
else
% % do that
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!