## How can I use for-loop to implement variable parameters?

### Dursman Mchabe (view profile)

on 13 Oct 2018
Latest activity Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 14 Oct 2018
Hi all, on the attached m-file I try to use for-loop to pass variable parameters, some how I get an error message that says:
Index exceeds the number of array elements (0).
Error in euler>odesfun (line 145)
CH = Parameter(1);
Error in euler (line 51)
y(i) = y0 + odesfun().*delta;
I followed the example given in this link:
but it seems like I make a mistake somewhere in the code.
function my_ode()
%main code
T0 = 293;
T1 = 300;
Tf2 = 293;
a = 0.2;
R = 1; % not defined in your code
C = 1; % not defined in your code
tchange = (T1-T0)/a;
for ii = 1:(tchange)+1
Tf(ii) = T0 + a*(ii-1);
d = (Tf(ii) - Tf2)/(R*C);
e = -2/(R*C);
% d and e need to be passed as parameters
[t,T] = ode45(@ode1,[0 336],293,[],[d,e]);
figure (1)
plot(t,T)
end
end
function dTdt = ode1(t,T,param)
d = param(1);
e = param(2);
dTdt = d - e*T;
end

### Stephen Cobeldick (view profile)

on 14 Oct 2018
Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 14 Oct 2018

Following the advice of old questions and answers is not a good idea, because the syntax can change. To parametrize a function you should follow the advice in the MATLAB documentation for your installed MATLAB version. Here is the online help for the current version:
It does not mention using a fifth input argument. It states that " ode45 only works with functions that use two input arguments, t and y. However, you can pass in extra parameters by defining them outside the function and passing them in when you specify the function handle." It also gives a link to a page that describes several ways to do this:
You can simply use an anonymous function to parametrize the function:
T0 = 293;
T1 = 300;
Tf2 = 293;
a = 0.2;
R = 1;
C = 1;
tchange = (T1-T0)/a;
for ii = 1:tchange+1
Tf(ii) = T0 + a*(ii-1);
d = (Tf(ii) - Tf2)/(R*C);
e = -2/(R*C);
fun = @(t,T) d - e*T;
[t,T] = ode45(fun,[0,336],293);
figure()
plot(t,T)
end