How do i solve this problem?

8 views (last 30 days)
I need to use matlab to evaluate this integral numerically using simpsons rule. The code below is what i've written so far, but there is a problem with it. The first part of the code i've commented out, this is the code which calculates the values for the integral at different points. Ive used 21 points of estimation and 20 strips.
Is there a way to calculate the values and store them into a matrix? Instead of calculating the matrix and then writing out the definition of the matrix like i've done below. It looks really terrible.
The below works fine for calculating the simpsons rule for 20 strips, but i would like to prompt the user to enter the number of strips to be used, how do i do this? Ive tried:
prompt('Please enter number of strips')
x = input(prompt)
Then set n = x
This doesnt work though.
%Matlab script to evalauate the integral of sin^3(x) betweeon 0 and pi/2,
%Where n = 20
%used to calcalate the values
% step = ((0.5*pi)/n);
% finish = pi*0.5;
% for i = 0:step:finish
%
% (sin (i)^3)
%
% end
n = 20;
v = [0,4.8298e-04,0.0038,0.0127,0.0295,0.0560,0.0936,0.1426,0.2031,0.2739,0.3536,0.4397,0.5295,0.6199,0.7074,0.7886,0.8602,0.9194,0.9635,0.9908,1];
esno = 0;
osno = 0;
simpval = 0;
finish = pi/2;
h = finish/n;
%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))

Accepted Answer

Rahul Kalampattel
Rahul Kalampattel on 9 Mar 2017
The syntax for a user prompt is prompt = 'text' rather than what you had.
prompt = 'Please enter number of strips: ';
n = input(prompt);
As far as calculating the values of the function at each point and storing them in a vector goes, Matlab allows you to do this quite easily. First you define a vector with the points you are interested in.
finish = pi/2;
h = finish/n;
points = 0:h:finish; % From 0 to 'finish' with steps of 'h'
Then, you can evaluate the function for each element of the vector. The '.^' notation is important, as it indicates you are carrying out the operation element-wise.
v = sin(points).^3;
Putting it all together, you get something like this:
% Matlab script to evaluate the integral of sin^3(x) between 0 and pi/2
prompt = 'Please enter number of strips: ';
n = input(prompt);
finish = pi/2;
h = finish/n;
points = 0:h:finish; % From 0 to 'finish' with steps of 'h'
v = sin(points).^3;
esno = 0;
osno = 0;
% 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))

More Answers (0)

Categories

Find more on Propagation and Channel Models in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!