How to get an n+2 column in matlab

51 Views Asked by At

function dy = SIR(t,y)

n=100;

dy=zeros(n+2,1);

for j=2:n

dy1=5*(n+1)*(y(1)+sum(y(j)))-n*y(1);

dy(j)=n*y(j-1)-n*y(j);

dy3 =-5*(n+1)*(y(1)+sum(y(j)));

dy4 =n*y(n);

dy=[dy1;dy(j);dy3;dy4];

end

Why is this giving me a vector of length 4? I want a vector of lenth n+2.

2

There are 2 best solutions below

2
On BEST ANSWER

It is difficult to understand exactly what you want the code to do. My best understanding is that dy1 is to be in position $1$, dy3 in position $n+1$, dy4 in position $n+2$ and positions $2-n$ are calculated using the loop. This can be corrected as follows.

It makes no sense to use sum(y(j)) as this is summing a single element. I have changed this to be sum(y) which adds the elements of y, as I think you meant to do.

Also, if n is the length of y, they you should use n=length(y); instead of hard coding the value.

function dy = SIR(t,y)

n = 100;

dy = zeros(n+2,1);

tempVal = 5*(n+1)*( y(1) + sum(y) );

dy(1) = tempVal - n*y(1);
for j=2:n
    dy(j) = n*( y(j-1) - y(j) );
end
dy(n+1) = -tempVal;
dy(n+2) = n*y(n);
0
On

The line dy=[dy1;dy(j);dy3;dy4]; is within your for-loop and assigns dy to a $4 \times 1$ vector.