フィルターのクリア

Index exceeds array bounds error

1 回表示 (過去 30 日間)
Martina Della Monica
Martina Della Monica 2019 年 8 月 6 日
Dear all,
I implemented this simple function:
function [SP_Simulation]=get_survivalprobability(a,b,w,dt,m,k)
for i=1:k
for j=1:m
hzrd(i,j)=exp(a(i)+b*w(i,j)) ;
end
end
h1=hzrd(1,:) ; % find a for the first row vector
SP1=(sum(exp(h1*-dt)))/m ;
for i=1:k-1
h=(hzrd(i,:)+hzrd(i+1,:))*-dt;
SP_others=sum(exp(h),2)/m ;
SP_Simulation=[SP1;SP_others];
end
end
whose main code to test is:
SP_termstruc=repmat(0.98,253,1);
m=3;
k=2;
b=0.01;
dt=0.5;
w=rand(253,100);
a0=[0 0]; % guess per fsolve
fun=@(a) (get_survivalprobability(a,b,w,dt,m,k)-SP_termstruc);
[a] = fsolve(fun,a0); % find f(a)=0
for i=1:k % find hazard rates with the new parameters a
for j=1:m
h(i,j)=exp(a(i)+b*w(i,j))
end
end
For the previous example, where m=3 (number of columns) and k=2(number of rows) , everything works. However, when I want to test this function for m=100 and k=253 it shows the error " Matrix dimensions must agree. Error in Tesi>@(a)(get_survivalprobability(a,b,w,dt,m,k)-SP_termstruc)
Could someone help me to understand what is wrong, please?
Thank you in advance
Martina

採用された回答

David K.
David K. 2019 年 8 月 6 日
The problem is a0. In the line
hzrd(i,j)=exp(a(i)+b*w(i,j)) ;
a needs to be have at least k elements for it to work. You set the first a as a0 so a0 needs to have k elements. It works when k = 2 because a0 = [0 0] but wont work for any larger values of k. Replace a0 with
a0 = zeros(1,k);
assuming you want a0 to be zeros.
  3 件のコメント
David K.
David K. 2019 年 8 月 6 日
Ah in my testing I did not change repmat. And since the new error is caused by a mistake in the function output itself my testing did not catch that error.
To fix this second problem, replace SP1 with SP_Simulation as such:
SP1=(sum(exp(h1*-dt)))/m ;
to
SP_Simulation=(sum(exp(h1*-dt)))/m ;
SP_Simulation=[SP1;SP_others];
to
SP_Simulation=[SP_Simulation;SP_others];
Martina Della Monica
Martina Della Monica 2019 年 8 月 6 日
Thank you so much, David. I really appreciate your help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by