Index exceeds array bounds error

3 次查看(过去 30 天)
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
Thank you so much, David. I really appreciate your help!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by