Index exceeds the number of array elements. Index must not exceed 1.

조회 수: 12 (최근 30일)
Haya Ali
Haya Ali 2023년 2월 6일
댓글: Haya Ali 2023년 2월 7일
Please help to resolve the error.
clear all; close all; clc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Simulation %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%value of constants
a1=0.7;a2=0.1;
omega1=20;omega2=40;
G=10;C12=0;C21=0.003;
dt=0.01; %step size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x1rec(1)=0.5;
y1rec(1)=0.5;
x2rec(1)=0.5;
y2rec(1)=0.5;
for i=2:1000
x1rec(i)=x1rec(i-1)+((a1-x1rec(i-1)^2-y1rec(i-1)^2)*x1rec(i-1)-omega1*y1rec(i-1)+G*C12*(x2rec(i-1)-x1rec(i-1)))*dt;
x2rec(i)=x2rec(i-1)+((a2-x2rec(i-1)^2-y2rec(i-1)^2)*x2rec(i-1)-omega2*y2rec(i-1)+G*C21*(x1rec(i-1)-x2rec(i-1)))*dt;
end

채택된 답변

Voss
Voss 2023년 2월 6일
The first time through the for loop, i is 2, so on the right-hand side of your equations you are accessing x1rec(1), x2rec(1), y1rec(1), and y2rec(1) and on the left-hand side of your equations you are setting x1rec(2) and x2rec(2).
Then, the second time through the for loop, i is 3, so you are accessing x1rec(2), x2rec(2), y1rec(2), and y2rec(2), but y2rec and y2rec only have one element each. That is, y1rec(2) and y2rec(2) haven't been calculated yet. This is the source of the error.
Maybe your code inside the loop should calculate y1rec(i) and y2rec(i) along with x1rec(i) and x2rec(i) somehow?

추가 답변 (1개)

Jonas
Jonas 2023년 2월 6일
you can initialize your array before the loop
a1=0.7;a2=0.1;
omega1=20;omega2=40;
G=10;C12=0;C21=0.003;
dt=0.01; %step size
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
numOfIterations=1000;
x1rec=zeros(1,numOfIterations);
y1rec=zeros(1,numOfIterations);
x2rec=zeros(1,numOfIterations);
y2rec=zeros(1,numOfIterations);
x1rec(1)=0.5;
y1rec(1)=0.5;
x2rec(1)=0.5;
y2rec(1)=0.5;
for i=2:numOfIterations
x1rec(i)=x1rec(i-1)+((a1-x1rec(i-1)^2-y1rec(i-1)^2)*x1rec(i-1)-omega1*y1rec(i-1)+G*C12*(x2rec(i-1)-x1rec(i-1)))*dt;
x2rec(i)=x2rec(i-1)+((a2-x2rec(i-1)^2-y2rec(i-1)^2)*x2rec(i-1)-omega2*y2rec(i-1)+G*C21*(x1rec(i-1)-x2rec(i-1)))*dt;
end
disp('finish')
finish

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by