MATLAB: My variable are not being recognized or are stuck inside of the loop

variable constants ode45 for lool

Hi all!
Im running a kinetic reaction, where i want in the code to ask for the input variable, such as, reactor lenght, initial pressure, density, and others.
And i want to use the variable provided to solve the ode45, and the ode45 is inside of for loop.
If i place the x=input('…:') inside of the loop it will ask me infinite times the values for those variable, however if i place it outside, my function in the ode no longer recongnized them.
I find it quite strange, specially since the variable appears in the workspace. Has anyone came across something like this? I provide the whole code in the following lines:
wsv = input('Please enter the WHSV(h-1): ');
T = [475
521
562
579
593];
c = [3605.8 5318
2304.9 5318
0 4514.5
0 3936.2
0 2971];
a0=[10;100000;1;100000];
[a,Rsdnrm,Rsd,ExFlg,OptmInfo,Lmda,Jmat]=lsqcurvefit(@kinetics,a0,T,c);
fprintf(1,'\tRate Constants:\n')
for k1 = 1:length(a)
fprintf(1, '\t\tTheta(%d) = %8.5f\n', k1, a(k1))
end
Cmod = kinetics (a,450:1:650);
plot(T,c, 'o')
hold on
plot(450:1:650,Cmod)
hold off
%tv = linspace(min(t), max(t));
%Cfit = kinetics(a, tv);
function C=kinetics(a,T)
a
C = zeros(length(T), 2);
c0=[3971.5;5318.6];
xspan = [0 : 0.1 : 0.7];
for i = 1 : length(T)
[z,Cv]=ode45(@(x,c) DifEq(x,c,T(i)),xspan,c0);
C(i,:) = Cv(end,:)
end
%end
%
function dC=DifEq(x,c,T)
WHSV=wsv
d_reactor = 0.148; % m (algae campaign data)

L_reactor = 0.7; % m (algae campaign data)
m_cat = 0.0486; % kg (algae campaign data)
R = 8.314 ; % J/mol*K
S = (d_reactor^2 / 4)*pi;
rho_cat = m_cat / (S * L_reactor);
rho_biocrude = 979.1;
P = (100*10^5); %Pa
HCP = 7.7*10^(-6);
CH2 = P * HCP;
Q = (((WHSV*m_cat)/3600)/rho_biocrude); % m^3/s
dcdx=zeros(2,1);
dcdx(1) = -((S * rho_cat) / Q) * a(1)* exp(-a(2) / (R * T)) * c(1) * CH2;
dcdx(2) = -((S * rho_cat) / Q) * a(3) * exp(-a(4) / (R * T)) * c(2) * (CH2.^(1.5)) ;
dC=dcdx;
end
end

Best Answer

Do NOT call input inside your functions (nor for that matter, have any user interaction, file import/export, etc.).
You need to parameterize the functions. The MATLAB documentation explains how:
For example, if you want to use the variable wsv inside of kinetics, then do this:
wsv = ...
[...] = lsqcurvefit(@(x,d)kinetics(x,d,wsv),...)
where:
function C = kinetics(a,T,w) % <- note third input argument!
You will need to do the same with DifEq too:
[...] = ode45(@(x,c) DifEq(x,c,T(i),w), ... )
% ^
where
function dC=DifEq(x,c,T,w) % <- note fourth input argument!
Curiously you have already parameterized the ode45 function, what is stopping you from extending that for wsv ?