How do i plot the integral against number points used?

2 ビュー (過去 30 日間)
Michael Lee
Michael Lee 2017 年 3 月 15 日
回答済み: Rik 2017 年 3 月 20 日
This currently the code i have for prompting the user for input for number of strips. I would like to be able to calculate the integral for n+1=1,2,3,4,5... and plot this against the sample points used. I dont have much of a clue on how to do this, i would suppose to use a for loop and then decrement the no of sample points used for each iteration.
Thanks, very new to matlab.
%Matlab script to evaluate the integral of sin^3(x) between 0 and pi/2
%Prompts the user for input number of strips
prompt = 'Please enter number of strips: ';
n = input(prompt);
%Declaration of constant and vectors
finish = pi/2;
h = finish/n;
points = 0:h:finish; % From 0 to 'finish' with steps of 'h'
esno = 0;
osno = 0;
%Carry out the operator element wise, for each element
v = sin(points).^3;
% Loop for finding sum of even terms
for j = 2:2:n
esno = esno + v(j);
end
% Loop for finding sum of odd terms
for k = 3:2:n-1
osno = osno + v(k);
end
simpval = (h/3)*(v(1) + 4*esno + 2*osno + v(n+1))
%Graphing the convergence of integral with no. of sample points
samplepoints = n+1;
samplepointsvector = 1:1:samplepoints
  4 件のコメント
Rik
Rik 2017 年 3 月 15 日
I think I would do something like this:
total_samples=20;
integral_value=zeros(1,total_samples);
for n_samples=1:total_samples
X=linspace(0,pi/2,n_samples+1);
Y=sin(X).^3;
integral_value(n_samples)=trapz(X,Y);
end
plot(1:total_samples,integral_value)
Please let me know if this is what you want, or explain how it doesn't do what you need.
Michael Lee
Michael Lee 2017 年 3 月 20 日
yeah thats perfect thank you

サインインしてコメントする。

回答 (1 件)

Rik
Rik 2017 年 3 月 20 日
copied from comments
total_samples=20;
integral_value=zeros(1,total_samples);
for n_samples=1:total_samples
X=linspace(0,pi/2,n_samples+1);
Y=sin(X).^3;
integral_value(n_samples)=trapz(X,Y);
end
plot(1:total_samples,integral_value)

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by