Index exceeds the number of array elements (5)

35 ビュー (過去 30 日間)
Kolleggerm1
Kolleggerm1 2019 年 10 月 7 日
コメント済み: Guanyang Liu 2021 年 3 月 17 日
I am solving Forward Euler for dy=x*y+1, x between 0 and 1, y(0)=0 h=.25
I have gotten the error message "Index exceeds the number of array elements (5)" after rearranging the code (because I was getting other error messages). How can I clear it up?
clc; clear all;
h=0.25; % step size
xmin=0;
xmax=1;
x=xmin:h:xmax; %x boundaries
n=length(x);
y=zeros(1,n);% Initial condition
for i=1:n
x0=0;
dy=(x(i+1)*y(i)+1);
x(i+1)=n*h;
y(i+1)=y(i)+h*dy;
end
figure(1)
hold on
plot (y,x,'b', 'linewidth',2)
title ('Forward Euler')
  1 件のコメント
Matt J
Matt J 2019 年 10 月 7 日
Kolleggerm1's comment moved here:
So I added a line to the for-loop to identify the max of i which seemed to solve the exceeding error, but now I get an error "Array indices must be positive integers or logical values" in line 10
clc; clear all;
h=0.25; % step size
xmin=0;
xmax=1;
x=xmin:h:xmax; %x boundaries
n=length(x);
y=zeros(1,n);% Initial condition
for i=1:n
i=0:1:4;
dy=(x(i+1)*y(i)+1);
x(i+1)=n*h;
y(i+1)=y(i)+h*dy;
end
figure(1)
hold on
plot (y,x,'b', 'linewidth',2)
title ('Forward Euler')

サインインしてコメントする。

採用された回答

the cyclist
the cyclist 2019 年 10 月 7 日
You have initialized x and y to be vectors of length 5. But in your for loop, i reaches the value value 5, and then you try to access x(i+1), which is x(6), which does not exist. You could run your for loop over just i = 1:n-1.
  6 件のコメント
the cyclist
the cyclist 2021 年 3 月 17 日
I did not fully understand your question.
I think you should open a new one, with your code included.
MATLAB is a procedural language, and always runs through the code in order.
Guanyang Liu
Guanyang Liu 2021 年 3 月 17 日
Thank you so much for your prompt reply! I'll start a new thread then

サインインしてコメントする。

その他の回答 (1 件)

Matt J
Matt J 2019 年 10 月 7 日
for i=1:n-1

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by