Azzera filtri
Azzera filtri

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

8 visualizzazioni (ultimi 30 giorni)
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:
https://www.mathworks.com/matlabcentral/answers/153998-ode45-not-enough-input-argument
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
Please help.

Risposte (1)

Stephen23
Stephen23 il 14 Ott 2018
Modificato: Stephen23 il 14 Ott 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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by