MATLAB: Index exceeds the number of array elements (4)

indexMATLAB

I'm trying to a model a CSTR. I'm trying to test out different volumetric flowrates ,F. I created a loop to run through the different flowrates but keep getting the error stated in the title. Can someone please help me figure this out?
function dcdt= myfunction(t,C, F)
cA0 =0.4;
cB0 =0.5;
cX0 =0;
cY0 =0;
cZ0 =0;
k1 = 5*10^-4;
k2 = 5*10^-2;
k3 = 2*10^-2;
V = 1;
%F = 0.01;
tau = V/F;
dcdt= [(cA0 -C(1))/tau - k1*C(1)*C(2);
(cB0 -C(2))/tau - k1*C(1)*C(2)-k2*C(2)*C(3)-k3*C(2)*C(4);
(cX0 -C(3))/tau + k1*C(1)*C(2)-k2*C(2)*C(3);
(cY0 -C(4))/tau + k2*C(2)*C(3)-k3*C(2)*C(4);
(cZ0 -C(5))/tau + k3*C(2)*C(4)];
end
initcon = [0.4, 0.6, 0, 0, 0];
F = [0:0.001:0.010];
X = zeros(size(F));
for i = 1:numel(F) %m^3/s
%ODE solver CSTR
[time, C] = ode45(@myfunction, [0,1500], initCon,[],F(i));
X(i) = max(C(:,3));
%X(i) = Ccstr1(end,3);
end
figure (3)
plot(F,X)
grid on
xlabel('Flow rate [m^3/s]')
ylabel('concentration c_X [mol/m^3]')

Best Answer

You were initializing a variable initcon but you were using a variable initCon . You happened to have an initCon in your workspace that was length 4 instead of the 5 needed for this code.
initCon = [0.4, 0.6, 0, 0, 0];
F = [0:0.001:0.010];
X = zeros(size(F));
for i = 1:numel(F) %m^3/s
%ODE solver CSTR
[time, C] = ode45(@myfunction, [0,1500], initCon,[],F(i));
X(i) = max(C(:,3));
%X(i) = Ccstr1(end,3);
end
figure (3)
plot(F,X)
grid on
xlabel('Flow rate [m^3/s]')
ylabel('concentration c_X [mol/m^3]')
function dcdt= myfunction(t,C, F)
assert(isscalar(F), 'F wrong size, %d elements', numel(F));
cA0 =0.4;
cB0 =0.5;
cX0 =0;
cY0 =0;
cZ0 =0;
k1 = 5*10^-4;
k2 = 5*10^-2;
k3 = 2*10^-2;
V = 1;
%F = 0.01;
tau = V/F;
dcdt= [(cA0 -C(1))/tau - k1*C(1)*C(2);
(cB0 -C(2))/tau - k1*C(1)*C(2)-k2*C(2)*C(3)-k3*C(2)*C(4);
(cX0 -C(3))/tau + k1*C(1)*C(2)-k2*C(2)*C(3);
(cY0 -C(4))/tau + k2*C(2)*C(3)-k3*C(2)*C(4);
(cZ0 -C(5))/tau + k3*C(2)*C(4)];
end