I can't find solution of sinusoidal function's by numerical methods
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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);
0 commentaires
Réponse acceptée
Jon
le 18 Oct 2019
Modifié(e) : Jon
le 18 Oct 2019
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
2 commentaires
Jon
le 18 Oct 2019
Modifié(e) : Jon
le 18 Oct 2019
I think your comment got out of synch with my answer. Please try the above suggestions. Most importantly initalize x(1) = a not x(1) = f(a). Note if a = 0 and f(a) = 0 then it won't matter which way you assign it. So your current code should still work for functions like sin(x) and sin(x)^2 as long as you start at a = 0, but still it makes no sense to have x(1) = f(a). For the function in your comment f = @(x) ((exp(-x^2)) * sin(x^2+1)) it will definitely make a difference as f(0) = 0.8415
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!