MATLAB: ??? Attempted to access f(0); index must be a positive integer or logical. Help me to solve this problem.

positive integer or logical

I was trying to find approximate value of function f(x)=Sin(x)
a =0; b =pi; N=20;
h = ((b-a)/N);
f= sin(x);
x=a:h:b;
Area= 0;
while (a<b)
Area = Area +(h/2)*(f(a) + f(a+h)); % using trapezoidal rule
a = a+h;
end
fprintf('Area = %f', Area);
??? Attempted to access f(0); index must be a positive integer or logical.
Error in ==> MenuCommands at 16
Area = Area +(h/2)*(f(a) + f(a+h));

Best Answer

Thomas - see anonymous functions for details on how to properly define an anonymous function. Your code
f = sin(x);
is valid if x is known, but if you wish to use it as a function as you are doing with
Area = Area +(h/2)*(f(a) + f(a+h));
then you need to define f as
f = @(x)sin(x);
Try the above and see what happens!