"Array indices must be positive integers or logical values"

5 次查看(过去 30 天)
for i=1:n
disp(i)
ti(i+1)=ti(i)+dt;
x1i(i+1)=x1i(i)+dt(V1i(i))
x2i(i+1)=x2i(i)+dt(V2i(i))
Using, this code I get the error message shown in the subject line, even if i change the updating to x1i(i)= ... this doesn't fix the problem.
Any advice?
  3 个评论
Rory Thiel
Rory Thiel 2023-3-22
function [x1i,x2i, ti] = BasicEuler (RHS1,RHS2,initial, t0, tf, dt)
%create arrays for all variables which change over time
ti=zeros(1,1000);
x1i=zeros(1,1000);
x2i=zeros(1,1000);
V1i=zeros(1,1000);
V2i=zeros(1,1000);
ti(1)=t0;
%%define initial conditions (at time = 0s)
x1i(1)=initial(1);
x2i(1)=initial(2);
V1i(1)=initial(3);
V2i(1)=initial(4);
n=(tf-t0)/dt; %number of loops
i=0;
while max(ti)<tf
i=i+1;
ti(i+1)=ti(i)+dt;
x1i(i+1)=x1i(i)+dt(V1i(i));
x2i(i+1)=x2i(i)+dt(V2i(i));
%Continue on to calculate new V1 and V2 using RHS eqs
end
Here I have tried using a while loop instead but this doesn't resolve the issue
Which I am calling with
[x1i, x2i,ti] = BasicEuler (RHS1,RHS2,initial, t0, tf, dt);
after with all the required inputs in the main script
Rory Thiel
Rory Thiel 2023-3-22
x1i(i+1)=x1i(i)+dt*(V1i(i));
Wasn't really a problem with indexing, I missed the * symbol after dt so it thought I was trying to search a dt array which is just a constant variable

请先登录,再进行评论。

回答(1 个)

Cris LaPierre
Cris LaPierre 2023-3-22
编辑:Cris LaPierre 2023-3-22
Your indices must be positive integer values (or logicals), as the error message states. It is therefore most likely either V1i(i) or V2i(i) are not returing an integer value, causing the error about invalid array indices when used to index into your variable dt.
a=1:3;
% This works
a(1)
ans = 1
% your error
a(1.5)
Array indices must be positive integers or logical values.

类别

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

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by