Index exceeds array bounds error

1 view (last 30 days)
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

Accepted Answer

David K.
David K. on 6 Aug 2019
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 Comments
David K.
David K. on 6 Aug 2019
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 on 6 Aug 2019
Thank you so much, David. I really appreciate your help!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!