In this program I am modeling the the population of rabbits and foxes. The mathematical model I use predicts that each year the number of rabbits and foxes in a region change with the following equations: Δr=Ar−Brf Δf=Crf−Df where Δr and Δf are the changes in number of rabbits and foxes after one year, r and f are the number of rabbits and foxes from the previous year, and A, B, C, D are parameters describing the predator-prey interaction of the two species. Also being modeled is the movement of foxes. In the program I assume that each year, half of the foxes in each region move to the four neighboring regions (up/down/left/right regions getting 1/8th of the foxes) while the other half stay within the region. Assume this migration happens instantaneously at the end of the year, after the population of rabbits and foxes have changed due to the predator-prey interaction. Assume the foxes can move out of the country but no foxes move back into the country. Assume that the rabbits do not move across regions. Write a function rabbitsandfoxes(R,F, A,B,C,D, withmigration) that takes the matrices R and F representing the populations of rabbits and foxes from the previous year, the constants A,B,C,D, and the withmigration argument specifying whether or not to model the migration of the foxes; and returns what the number of rabbits and foxes would be after one year. If withmigration is not specified, assume it to be true.
Here's my code:
function [newR,newF]=rabbitsandfoxes(r,f,A,B,C,D,withmigration)if ~exist('withmigration','var') withmigration=true;if withmigration==truenewR=abs(A.*r-B.*r.*f);F=abs((C.*r.*f)-(D.*f))+f;[R,C]=size(f);newF=padarray(F/2,[1 1],'circular');newF(1:R,2:C+1)=newF(1:R,2:C+1)+F/8;newF(2:R+1,1:C)=newF(2:R+1,1:C)+F/8;newF(3:R+2,2:C+1)=newF(3:R+2,2:C+1)+F/8;newF(2:R+1,3:C+2)=newF(2:R+1,3:C+2)+F/8;newF=newF(2:R+1,2:C+1);elseif withmigration==falsenewR=abs(A.*r-B.*r.*f)+r;newF=abs((C.*r.*f)-(D.*f))+f;endend
For some reason my newR values are always off, but newF is correct. I am trying to figure out if it has something to do with calculating the equation wrong?
Best Answer