I can't find solution of sinusoidal function's by numerical methods
3 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Jon
2019 年 10 月 18 日
編集済み: Jon
2019 年 10 月 18 日
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 件のコメント
Jon
2019 年 10 月 18 日
編集済み: Jon
2019 年 10 月 18 日
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!