MATLAB: I can’t find solution of sinusoidal function’s by numerical methods

iterationnumericaltrigonometric

I tried to write a code for a rectangle method(integral). Actually i saw same problem with other numerical methods too.
My problem is occur when i write a function like f = sin(x), sin(x^2) or x + sin(x^2) etc. (and i wrote a=0 and b = pi)
This code solves equations which doesn't have a trigonometric parameters.
How can i edit my code?
f =@(x) x^2;
a = 1;
b = 4;
n = 2;
h = (b-a)/n;
x(1) = f(1);
for j = 1:(n)
x(j+1) = x(1) + j*h;
c(j) = (x(j+1) + x(j)) / 2;
end
for i = 1:n
s(i) = h * f(c(i));
end
fx = sum(s);
fprintf('\n f(x) = %f',fx);

Best Answer

I assume that you are trying to approximate the integral of f(x) between x = a and x = b.
You are initializing x incorrectly. You have
x(1) = f(1);
should be
x(1) = a;
Also you have n set to be equal to 2, but you will need many more points than this to get an accurate answer. Try with for example n = 100
Actually you can replace all of your code with just a few lines taking advantage of MATAB's ability to deal directly with vectors.
f =@(x) sin(x.^2);
a = 0;
b = pi;
n = 100;
h = (b-a)/n;
x = linspace(a,b,n);
c = (x(2:end)+x(1:end-1))/2;
fx = sum(h*f(c))
% check your result with MATLAB's built in integration routinne
fquad = integral(f,a,b)
If for some reason you really want to break it down and see each step in a loop it would be clearer and more efficient to just march through in one loop:
f =@(x) sin(x.^2);
a = 0;
b = pi;
n = 100;
h = (b-a)/n;
x1 = a;
fx = 0;
for j = 1:n
x2 = x1 + h;
c = (x1 + x2 )/2;
fx = fx + f(c)*h;
x1 = x2;
end
Finally, I would note that since your points are regularly spaced, there is no need to find the center of each interval, you can calculate it directly. So you could just use:
c = a+h/2:h:b