matrix indexation and loops over a specific set within a vector
1 次查看(过去 30 天)
显示 更早的评论
I have the following definitions
long = 1000;
init = 500;
N = init+long;
T = init+1:N-1;
T1 = init+2:N;
I then fill the vectors that I want according to this loop,
for t=1:N+1
Rk(t)=1+A(t)*alpha*kh(t).^(alpha-1)-delta;
Yi(t)=A(t)*(1-alpha)*kh(t).^alpha - A(t)*alpha*kh(t).^(alpha-1)+eta(t);
Rap(t)=Rk(t).^(1-gamma)+(1-gamma)*Rk(t).^(-gamma)*theta(t)*Yi(t)-0.5*gamma*(1-gamma)*(theta(t)*Yi(t)).^2;
end
Finally, I compute some new vectors according to this loop
for t=T1
fi1(t)=(v(t).^(1-gamma))*(Rk(t))*(Yi(t)'); % Expectations 1
fi2(t)=((v(t).^(1-gamma))*(Yi(t)).^2);
fi3(t)=(((v(t).^(1-gamma))*Rap(t)).^(1/(1-gamma)));
end
So, from the last loop I aim into getting a vector of size T1, but instead I receive a 1x1500 vector.
My scope is essentially to take all the numbers in vectors, v, Rk, Yi, from exactly the region that T1 specifies (i.e 502:1500), so I should get the 1x999, and not the 1x1500 vector.
So I suppose even if someone stars with an index 502 to count the loop, Matlab still understand this as 1, and loops until N, which is the end point of T1.
Can somebody tell me how should amend the code in order to get what I described above.
0 个评论
回答(1 个)
Guillaume
2015-2-12
编辑:Guillaume
2015-2-12
If you start with an index with an index 502 to count the loop, Matlab understands this as 502.
The issue is with your assignment. You assign the result to indices 502 to 1500, so matlab automatically fills up indices 1 to 501 with zeros. Hence you end up with vectors of size max(T1). To fix this, offset your assignment indices back to 1:
for t = T1
fi1(t-T1(1)+1)=(v(t).^(1-gamma))*(Rk(t))*(Yi(t)'); %why is there a conjugate transpose here?
fi2(t-T1(1)+1)=((v(t).^(1-gamma))*(Yi(t)).^2);
fi3(t)=(((v(t).^(1-gamma))*Rap(t)).^(1/(1-gamma)));
end
If gamma is scalar though, the above is simply:
fi1 = (v(T1).^(1-gamma)).*(Rk(T1)).*(Yi(T1)'); %no loop!
fi2 = ((v(T1).^(1-gamma)).*(Yi(T1)).^2);
fi3 = (((v(T1).^(1-gamma)).*Rap(T1)).^(1/(1-gamma)))
2 个评论
Guillaume
2015-2-12
Sorry, I made a mistake (and edited my original answer). I should have replaced your matrix multiplications *, but element by element multiplication .*, in my simplification.
If all you want is element by element operation, then use dots on every operator. It will be a lot faster than loops.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!