Euler's Method
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
1 commentaire
Darshan Ramakant Bhat
le 17 Avr 2017
Modifié(e) : Darshan Ramakant Bhat
le 17 Avr 2017
why are you passing sin(X) to your method. According to your assignment first argument should be function handle. In this function you are suppose to implement the logic of the Euler method. Please read the following doc about function handles:
Réponses (0)
Voir également
Catégories
En savoir plus sur Time-Frequency Analysis dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!