Why does this function handle not take the inputs?

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

"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.
Ok so when I call cos since it only depends on X is there a way to suppress that Y in the equations?

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

 채택된 답변

Stephen23
Stephen23 2017년 4월 23일
편집: Stephen23 2017년 4월 23일
The problem has nothing to do with your function handle. It is (exactly as the error message states) solely because the way you call cos:
cos(X,Y)
does not make any sense: cos only has one input.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

질문:

2017년 4월 23일

댓글:

2017년 4월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by