Why does this function handle not take the inputs?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
Stephen23
2017년 4월 23일
"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.
채택된 답변
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!