Why does this function handle not take the inputs?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mohannad Abboushi
am 23 Apr. 2017
Kommentiert: Mohannad Abboushi
am 23 Apr. 2017
So I have to approximate the value of sin(x) using the Runge-Kutta method. Here's my code:
function [X,Y]=rungekutta(fprime, timespan, y0, h)
if ~exist('h','var')
h=.1;
end
Y(1)=y0;
X(1)=timespan(1);
i=2;
while X(end)<timespan(end)
X(i)=X(i-1) + h;
k1 = h*fprime(X(i-1),Y(i-1));
k2 = h*fprime(X(i-1+h/2),Y(i-1)+k1/2);
k3 = h*fprime(X(i-1+h/2),Y(i-1)+k2/2);
k4 = h*fprime(X(i-1+h),Y(i-1)+k3);
Y(i) = Y(i-1) + (k1+2*k2+2*k3+k4)*h/6; % Approx soln
i=i+1;
end
X=X';
Y=Y';
abs_err=mean(abs(Y-sin(X)));
plot(X,Y);
xlabel('Time(seconds)'); ylabel('Function Y');
title('Runge-Kutta Method');
hold on
plot(X,sin(X));
legend('Approximation','sin(x)');
display=fprintf('The absolute error is %f',abs_err);
When I type in the command window [X,Y]=rungekutta(@(X,Y)(cos(X,Y)), [0 10], sin(0), .5) using the my desired parameters, it gives me an error with cos saying "too many input arguments". Is this because I created the function handle within the input?
2 Kommentare
Stephen23
am 23 Apr. 2017
"Is this because I created the function handle within the input?"
No, where you create the function handle is totally unrelated to the fact that you call cos with the wrong number of inputs.
Akzeptierte Antwort
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!