Convert fortran code to Matlab code C - Get result as complex numbers

조회 수: 14 (최근 30일)
heidi pham
heidi pham 2018년 12월 24일
편집: heidi pham 2018년 12월 29일
Hello,
I tried to convert a fortran code to matlab code. I don't know why I get very weird resutl after running my Malab code (the result comprise of complex numbers).
Here is the fortran code http://www.jonathanheathcote.com/Macro2/FYMHW1
If someone could see what did I do wrong in converting, please kindly help me. Thanks so much.
% set parameter values
%
theta = 0.4; % production parameter
beta = 0.95; % subjective discount factor
delta = 0.1; % capital depreciation rate
A=6.0476;
% Horizon
T=38; %which is "capt" in fortran code
% Sequence of capital and consumption
kseq=zeros(T+1,1);
cseq=zeros(T+1,1);
%Initial capital
kseq(1)=10;
% Guess the range of initial consumption
cguessl=1;
cguessh=10;
%Iteration parameter
iter=0;
tol=0.01;
while gapk > 0.01 && iter < 1000
cguess=0.5*(cguessl+cguessh);
cseq(1)=cguess;
for i = 2:T+1
%Law of motion of capital
kseq(i) = A*(kseq(i-1))^theta+(1-delta)*kseq(i-1)-cseq(i-1);
%check whether capital goes negative, if so reduce guess for
%consumption c(1)
if kseq(i)<0
cguessh=cguess;
else
cseq(i)=beta*(1+theta*A*(kseq(i))^(theta-1)-delta)*cseq(i-1);
end
end
%Check terminal capital and adjust bounds of cguess effectively
if kseq(T+1)>0
cguessl=cguess;
else
cguessh=cguess;
end
gapk = abs(kseq(T+1));
iter=iter+1;
end

채택된 답변

Walter Roberson
Walter Roberson 2018년 12월 24일
You have
kseq(i) = (kseq(i-1))^theta+(1-delta)*kseq(i-1)-cseq(i-1);
%check whether capital goes negative, if so reduce guess for
%consumption c(1)
if kseq(i)<0
cguessh=cguess;
else
cseq(i)=beta*(1+theta*(kseq(i))^(theta-1)-delta)*cseq(i-1);
end
In the case kseq(i) < 0, you set cguessh but you do not change kseq(i) . Then on the next iteration of the for i, kseq(i-1) will refer to the negative value, and you raise the negative value to theta. MATLAB defines the element-wise ^ operator as A.^B = exp(log(A)*B) and so when A < 0 the log(A) is complex and the whole result ends up complex unless B is an integer, even if there is a negative real number C such that C^(1/B) = A.
  댓글 수: 6
Walter Roberson
Walter Roberson 2018년 12월 25일
Might as well use the version I posted.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Fortran with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by