How to fix "index exceeds number of arrays error (1)" on my code

1 vue (au cours des 30 derniers jours)
Natalia Gonzalez
Natalia Gonzalez le 21 Fév 2019
Below is my function script:
function dcdt = func3a1(t,c)
global n aEG aCBH aBG Km1 Km2 Km3 Kg1 Kg2 Kg3 Kc1 Kc2 c0
A = 0;
for j = 3:n
A = A + c(j);
B = 0;
for k=3:n
B = B +(k-1)*c(k);
a = aEG./(B+Km1.*(1+c(1)./Kg1 + c(2)./Kc1));
b = aCBH./(A+Km2.*(1+c(1)./Kg2 + c(2)./Kc2));
r = aBG./(c(2)+Km3.*(1+c(1)./Kg3));
%differential equations of c1 and c2
dcdt(2)= 2*a*A + b*(A+c(4)) - r*c(2);
dcdt(1)= 2*a*A + b*c(3) + 2*r*c(2);
%differential equations for c(n=3:98)
for i = 3:n-2
dcdt(i,1) = a*2*(A-(i-1)*c(i))+b*(c(i+2)-c(i));
%differential equation for n=100 and n=99
dcdt(n) = a*(n-1)*c(n)-b*c(n);
dcdt(n-1) = a*(2*A-(n-2)*c(n-1));
And this is my ode solver script:
global n aEG aCBH aBG Km1 Km2 Km3 Kg1 Kg2 Kg3 Kc1 Kc2 c0
% Initial conditions and setup
n = 100;
c0 = 0.6; %mmol/L
aEG = 7; %mmol/L/h
aCBH = 12; %mmol/L/h
aBG = 6; %mmol/L/h
Km1 = 10; %mmol/L
Km2 = 1; %mmol/L
Km3 = 1; %mmol/L
Kg1 = 1; %mmol/L
Kg2 = 1; %mmol/L
Kg3 = 1; %mmol/L
Kc1 = 20; %mmol/L
Kc2 = 20; %mmol/L
x = (0:0.1:5); % the range of x
z = zeros(size(x)); % allocate the result y
y(1) = c0; % the initial y value
% The loop to solve the DE
[t,c] = ode15s(@func3a1,x,y);
xlabel('Time (h)');
I keep getting this error when I run my function and ode scripts:
Index exceeds the number of array elements (1).
Error in func3a1 (line 9)
A = A + c(j);
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode15s (line 150)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in Ex1_3a (line 25)
[t,c] = ode15s(@func3a1,x,y);
Why does this keep appearing and how can I fix it?

Réponses (1)

Kevin Chng
Kevin Chng le 22 Fév 2019
Your error is from
for k=3:n
B = B +(k-1)*c(k);
In your main script, n = 100, means that you are going to indexing c(3),c(4),..., until c(100).
The size of c is inherit from y in the main script, y has one size which is y(1) = c0.
Therefore, when accessing c(3), the index is exceed the dimenson of c.

Community Treasure Hunt

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

Start Hunting!

Translated by