Euler Method function creation

조회 수: 7 (최근 30일)
Bronx Zoo
Bronx Zoo 2017년 4월 15일
편집: James Tursa 2017년 4월 17일
My homework asks me to:
Write a function [X,Y]=eulermethod(fprime, timespan, y0, h=0.1) where
fprime: function handle representing derivative of f for a given value of x.
timespan=[x0 xend]: starting and ending values of x
y0: f(x0), value of function at x=x0.
h: step size (default h=0.1)
Your function should calculate using Euler's method and store in Y, the successive values of f(x) for X=x0..xend. It is okay if the last entry in X does not reach exactly xend.
Use the eulermethod() function you wrote to approximate the value of sin(x), for x=0..10. Compare the values of sin(x) and the approximated values by showing them on the same plot. What is the average absolute error in your approximated values (average for entire x=0..10, not just for x=10)?
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The function that I currently have is:
function [X,Y] = eulermethod(fprime, timespan, y0, h)
if nargin<4, error('at least 4 input arguments required'), end
X_low = timespan(1);
X_high = timespan(2);
if ~ (X_high>X_low), error('upper limit must be greater than lower limit'), end
X = (X_low:h:X_high)';
n = length(X);
if X(n)<X_high
X(n+1) = X_high;
n = n+1;
X(n)=X_high;
end
Y = y0*ones(n,1);
for i = 1:n-1
Y(i+1) = Y(i) + fprime(X(i),Y(i))*(X(i+1)-X(i));
end
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- However, when I try to run the function in the MATLAB command using
eulermethod (sin(X), [0,10],10, .1)
I get an error saying
"Subscript indices must either be real positive integers or logicals"
and
"Error in eulermethod (line 18) Y(i+1) = Y(i) + fprime(X(i),Y(i))*(X(i+1)-X(i));"
Can you please help me correct this error? I have tried changing the y0 value and the error still exists. Thank you!
  댓글 수: 2
Andrew Newell
Andrew Newell 2017년 4월 17일
You entered sin(X) for some unspecified value of X instead of a function handle, for example:
eulermethod (@sin, [0,10],10, .1)
However, that's not right either, because they ask for the derivative of sin, which is ...?
James Tursa
James Tursa 2017년 4월 17일
편집: James Tursa 2017년 4월 17일
In addition, OP will need a custom function handle that takes two inputs (current values of X and Y) based on how "fprime" is being used in the code.

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

답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by