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

1 次查看(过去 30 天)
Below is my function script:
function dcdt = func3a1(t,c)
global n aEG aCBH aBG Km1 Km2 Km3 Kg1 Kg2 Kg3 Kc1 Kc2 c0
%summations
A = 0;
for j = 3:n
A = A + c(j);
end
B = 0;
for k=3:n
B = B +(k-1)*c(k);
end
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));
end
%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));
end
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);
%plots
figure(1)
plot(t,y(:,1),t,y(:,2));
xlabel('Time (h)');
ylabel('Concentrations');
legend('c1','c2');
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?

回答(1 个)

Kevin Chng
Kevin Chng 2019-2-22
Your error is from
for k=3:n
B = B +(k-1)*c(k);
end
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by