필터 지우기
필터 지우기

Why deosnt this work?

조회 수: 1 (최근 30일)
Michael Lee
Michael Lee 2017년 3월 20일
댓글: Michael Lee 2017년 3월 20일
Im trying to use simpsons rule to evaluate an integral, but odd numbers dont work for simpsons. So im testing whether the number is even or not before calculating the integral. Whats the problem here?
%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);
if mod(n,2) == 0
%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
total_samples=n;
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)
else
exit(0);
  댓글 수: 2
Adam
Adam 2017년 3월 20일
So what is the problem? Error? Incorrect result? No result?
Michael Lee
Michael Lee 2017년 3월 20일
Sorry should have said that at first. Just says continue entering statement.

댓글을 달려면 로그인하십시오.

채택된 답변

Steven Lord
Steven Lord 2017년 3월 20일
You haven't ended the if / else / end statement you started with if mod(n,2) == 0. If you put this code in the Editor, select all the code, right click, and select Smart Indent in the context menu you'll see that the if on line 5 lines up with the else on line 32, but there's no corresponding end.
FYI you probably don't want to call exit on line 33; that would quit MATLAB altogether.
  댓글 수: 1
Michael Lee
Michael Lee 2017년 3월 20일
Ahh right, rookie mistake. My apologies. I should probably use a while loop? To prompt user to enter till the number of strips is even?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by