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?

请先登录,再进行评论。

 采纳的回答

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 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by