# Euler's Method

조회 수: 1 (최근 30일)
Mikela Petersen 2020년 8월 16일
답변: Rafael Hernandez-Walls 2020년 8월 16일
I'm getting an error that reads "Error in myeuler (line 22)
y(i+1) = y(i) + (dx * f(x(i),y(i)));"
I don't exactly know what I'm doing wrong or even where to look in this line to see what's wrong.
% must call from edrive.m or other
% required input arguments: RHS function of two variables f,
% vector x of length n+1,
% init val c
% computed output argument: y\in\R^{n+1} approximate solution
function y = myeuler(f,x,c)
% approximates sol to y' = f(x,y) over [a,b] with y(a)=c
% via n steps of Euler's method
for n = [10, 20, 40, 80, 160]
a = 0; b = .5; c = .25;
x = [a:n+1:b];
f = @(x,y) (x.^3);
dx = (x(end)-x(1))/n;
y = [c ; zeros(n,1)];
for i = 1: n
y(i+1) = y(i) + (dx * f(x(i),y(i)));
end
end
##### 댓글 수: 2없음 표시없음 숨기기
Image Analyst 2020년 8월 16일
You forgot to give us the actual error. That means ALL the red text, not just a small snippet of it. By the way, your f does not seem to use y at all:
f = @(x,y) (x.^3);
You can see that it just returns x cubed. The y value is ignored.
Mikela Petersen 2020년 8월 16일
the error is the first thing that was listed:
>> myeuler
Index exceeds the number of array elements (1).
Error in myeuler (line 22)
y(i+1) = y(i) + (dx * f(x(i),y(i)));

댓글을 달려면 로그인하십시오.

### 답변 (2개)

Walter Roberson 2020년 8월 16일
for n = [10, 20, 40, 80, 160]
a = 0; b = .5; c = .25;
x = [a:n+1:b];
Consider the first case, n = 10 . Then
a = 0; b = .5; c = .25;
x = [0:10+1:.5]
but 0:11:.5 is going to give you just 0 .
The number in the middle in a a:b:c operation is the increment, not the number of elements to generate. To generate a particular number of elements,
x = linspace(a, b, n+1);
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Rafael Hernandez-Walls 2020년 8월 16일
for n = [10, 20, 40, 80, 160]
a = 0; b = .5; c = .25;
x = linspace(a,b,n);%[a:n+1:b];
f = x.^3;
dx = x(2)-x(1);%(x(end)-x(1))/n;
y = [c ; zeros(n-1,1)];
for i = 1: n-1
y(i+1) = y(i) + dx * f(i);
end
plot(x,y),hold on
end

댓글을 달려면 로그인하십시오.

### 카테고리

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

### Community Treasure Hunt

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

Start Hunting!

Translated by