title: Using interpolation outside function definition in solution using Runge-Kutta 4th order
body: <p>I have written MATLAB code to solve the following systems of differential equations.</p>
  
  <p><a href="https://i.stack.imgur.com/37srI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/37srI.png" alt="enter image description here"></a><br>
  with <a href="https://i.stack.imgur.com/3Iarh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Iarh.png" alt="enter image description here"></a> 
  where <a href="https://i.stack.imgur.com/cfvrP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cfvrP.png" alt="enter image description here"></a> 
  and    <em>z<sub>2</sub></em> = <em>x<sub>2</sub></em> + (1+<em>a</em>)<em>x<sub>1</sub></em></p>
  
  <pre><code>a = 2;
  k = 1+a;  
  b = 3;
  ca = 5;
  cb = 2; 
  
  theta1t = 0:.1:10;
  theta1 = ca*normpdf(theta1t-5);
  
  theta2t = 0:.1:10;
  theta2 = cb*ones(1,101);
  
  h = 0.05;
  t = 1:h:10;
  
  y = zeros(2,length(t));  
  
  y(1,1) = 1;  % &lt;-- The initial value of y  at time 1
  y(2,1) = 0;  % &lt;-- The initial value of y' at time 1
  
  f = @(t,y) [y(2)+interp1(theta1t,theta1,t,'spline')*y(1)*sin(y(2));
              interp1(theta2t,theta2,t,'spline')*(y(2)^2)+y(1)-y(1)-y(1)-(1+a)*y(2)-k*(y(2)+(1+a)*y(1))];
  
  for i=1:(length(t)-1)  % At each step in the loop below, changed y(i) to y(:,i) to accommodate multi results
     k1 = f( t(i)      , y(:,i)         );
     k2 = f( t(i)+0.5*h, y(:,i)+0.5*h*k1);
     k3 = f( t(i)+0.5*h, y(:,i)+0.5*h*k2);
     k4 = f( t(i)+    h, y(:,i)+    h*k3);
     y(:,i+1) = y(:,i) + (1/6)*(k1 + 2*k2 + 2*k3 + k4)*h; 
  end 
  
  plot(t,y(:,:),'r','LineWidth',2);
  legend('RK4');
  xlabel('Time')
  ylabel('y') 
  </code></pre>
  
  <p>Now what is want to do is define the interpolations/extrapolations outside the function definition like </p>
  
  <pre><code>theta1_interp = interp1(theta1t,theta1,t,'spline');
  theta2_interp = interp1(theta2t,theta2,t,'spline');
  f = @(t,y) [y(2)+theta1_interp*y(1)*sin(y(2));
             theta2_interp*(y(2)^2)+y(1)-y(1)-y(1)-(1+a)*y(2)-k*(y(2)+(1+a)*y(1))];
  </code></pre>
  
  <p>But this gives the error
  <a href="https://i.stack.imgur.com/NC4C1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NC4C1.png" alt="enter image description here"></a></p>
  
  <p>Please suggest a solution to this issue.</p>