Euler Method function creation
7 次查看(过去 30 天)
显示 更早的评论
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
2017-4-17
eulermethod (@sin, [0,10],10, .1)
However, that's not right either, because they ask for the derivative of sin, which is ...?
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!