I have a non ode function that calculates based on the previous time step of a time vector and spatial variable vector.
One of the parameters in this function is constant. However, I want to make that parameter a variable, which will change based at a given time.
Here is some example code to make this clear.
nstrains = 10;
param = .3*rand(1,nstrains);
strtime = rand(1,nstrains);
strtime = round(strtime);
strtime = sort(strtime);
initialconds = .5
t=0:.1:10; %time vector
x=1:.1:10; %spatial vector
k = zeros(numel(x),numel(t))
k = zeros(numel(x)/2,1) = initialconds
for i = 1:(numel(t)-1)
for j = 2:(numel(x)-1)
k(j,i+1) = 5*2+c(j+1,i)+param*c(j,1)+param
end
end
If param was held constant, this would be no problem. What I want to do is have a vector of random numbers for param, that enter random number for param at random times. The random time is determined by strtime.
So for example, if strtime vector = [2 4 9 10], and
param vector = [.21 .01 .25 .05]
First, I want an initial param value at time 0 = .2 (arbitrary). As soon as my
time vector matches with my strtime vector, which in this example is 2, then
my param value is updated to .21. .21 will be used at each time step until my
time vector matches my strtime vector again, which in this case, would be 4. By
time step 4, .01 is used as my param value, and so on.
I cannot really figure out how to get this down since the function is indexed in such a way. Is there a way to do this whilst keeping the function indexed the way it is, just somehow updating param to the new value determined by strtime vector?
Thanks, and hope I was clear enough.
Create a vector, the same size as your time vector
t, with the appropriate parameter value for each time.Taking your example data, here is one way to do it:
First, at the beginning of the strtime and param vectors, add the initial conditions (t>=0, param starts as .2).
Next, for each element in
t, find the largest element instrtimethat is less-than-or-equal-to that time point, and use that index to find the appropriate param. Here, I’ve done this witharrayfunrather than implementing it as aforloop, though conceptually they are the same.Now you’ve got a vector,
p, which you can index into withi(replaceparamin your loop section withp(i)).