Index exceeds array bounds error

조회 수: 7 (최근 30일)
Martina Della Monica
Martina Della Monica 2019년 8월 6일
댓글: 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by