Step Input CSTR Matlab Code
Step Input CSTR Matlab Code
x = linspace(0, L, nx)';
t = linspace(0, tmax, nt);
C = zeros(nx, nt);
C(:, 1) = 0;
C(1, :) = C0;
for j = 1:nt-1
for i = 2:nx-1
C(i, j+1) = C(i, j) + alpha * (C(i+1, j) - 2*C(i, j) + C(i-1, j)) -
beta * (C(i, j) - C(i-1, j));
end
C(nx, j+1) = C(nx-1, j+1);
end
F_n = C(nx,:)/C0;
E_n = gradient (F_n,dt);
E_n = E_n/trapz(t,E_n);
tm_n = trapz(t, t.*E_n);
sigma2_n = trapz(t, (t-tm_n).^2.*E_n);
figure(1)
subplot(2,1,1)
plot(t, F_n, 'b-', 'LineWidth', 2);
title('Step Response at CSTR Outlet (Finite diffrence solution');
xlabel('Time (min)');
ylabel('F-curve -->');
legend('F-curve');
grid on
subplot(2,1,2)
plot(t, E_n, 'r--', 'LineWidth', 1.5);
title(['RTD Response (Step input) of CSTR Outlet (Finite diffrence
solution)\newlineMean residence time = ',...
num2str(tm_n,3), ' s, Variance (num) = ', num2str(sigma2_n,4),' s^2']);
xlabel('Time (min)');
ylabel('E-curve -->');
legend('E-curve');
grid on
Ca = zeros(nx, nt);
for j = 1:nt
for i = 1:nx
if t(j) > 0
term1 = 0.5 * erfc((x(i) - u*t(j))/(2*sqrt(D*t(j))));
term2 = 0.5 * exp(u*x(i)/D) * erfc((x(i) +
u*t(j))/(2*sqrt(D*t(j))));
Ca(i, j) = C0 * (term1 + term2);
end
end
end
F_a = Ca(nx,:)/C0;
E_a = gradient (F_a,dt);
E_a = E_a/trapz(t,E_a);
tm_a = trapz(t, t.*E_a);
sigma2_a = trapz(t, (t-tm_a).^2.*E_a);
figure(2);
subplot(2,1,1)
plot(t, F_a, 'b-', 'LineWidth', 2);
title('Step Response at CSTR Outlet (Analytical Solution)');
xlabel('Time (min)');
ylabel('F-crve -->');
legend('F-curve');
grid on
subplot(2,1,2)
plot(t, E_a, 'r--', 'LineWidth', 1.5);
title(['RTD Response (Step input) of CSTR Outlet (Analytical
Solution)\newlineMean residence time = ',...
num2str(tm_a,3), ' s, Variance (analytic) = ', num2str(sigma2_a,4),'
s^2']);
xlabel('Time (min)');
ylabel('E-curve -->');
legend('E-curve');
grid on
figure(3);
plot(t, F_n, 'b-', 'LineWidth', 2);
hold on;
plot(t, F_a, 'r--', 'LineWidth', 1.5);
title('Step Response at CSTR Outlet \newlineComparison b/w Solutions of
Nemerical method and Analytical metod');
xlabel('Time (min)');
ylabel('F -->');
legend('Numerical solution Response', 'Analytical solution response');
grid on;
figure(4);
plot(t, E_n, 'b-', 'LineWidth', 2);
hold on;
plot(t, E_a, 'r--', 'LineWidth', 1.5);
title('RTD of CSTR for step input \newlineComparison b/w RTDs of Nemerical
method and Analytical metod');
xlabel('Time (min)');
ylabel('E -->');
legend('Numerical solution RTD', 'Analytical solution RTD');
grid on;