MATLAB: How to replace k-th diagonal by vector

for loopreplace k-th diagonal

I have a code here that give me errors. In the code I am computing a i-th dot product and want to replace this values on the i-th super diagonal.
lambda=0.42;
n=100;
p=0.005;
P=zeros(1001,1001);
for i=1:1000
a=i:1000;
b=a-i;
v=poisspdf(a,lambda);
w=binopdf(b,n,p);
c=dot(v,w);
d=size(diag(P,i),1);%this is the size of the vector with elements of the kth diagonal
e=c*ones(d,1);
diag(P,i)=e;
end
But matlab gives me an error saying:
Subscript indices must either be real positive integers or logicals.
Error in pdfnumber (line 18)
diag(P,i)=e;
Then I tried a more simple code. But is only replaces the 1 super diagonal for me, while i runs from 1 to 1000.
for i=1:1000
a=i:1000;
b=a-i;
v=poisspdf(a,lambda);
w=binopdf(b,n,p);
c=dot(v,w);
P(i,i+1)=c;
end
What am I doing wrong?

Best Answer

You can't use diag to assign to diagonales of a matrix, only to get them. The simplest way to assign to the diagonales is to replace:
d=size(diag(P,i),1);%this is the size of the vector with elements of the kth diagonal
e=c*ones(d,1);
diag(P,i)=e;
by
P(i*size(P, 1)+1:size(P, 1)+1:end) = e;
which simply computes the linear indices of the diagonal elements.