Integrating f(x) with Trapezium Rule & Plotting for Different Values of C

AI Thread Summary
The discussion focuses on integrating the function f(x) = x^3 + tan(x) + C using the trapezium rule between x = 2 and x = 4 with a step size of 0.1. The original code successfully calculates the integral but fails to plot results for varying values of C. A solution was provided, suggesting the addition of an outer loop to iterate through different C values and store the area results in an array. The modified code allows for plotting all calculated areas on the same graph. This approach effectively addresses the plotting issue while maintaining the integration calculations.
Rachelross
Messages
3
Reaction score
0

Homework Statement


Write a script file to integrate the function f(x)=x^3+tan(x)+C using the trapezium rule.Calculate the integral between the end points x=2 and x=4 with strip size 0.1.Calculate the integral for range of values from 1 to 3 in steps of 0.1.plot the integral obtained for different values of C?


Homework Equations


I wrote the code and it is calculating the correct integrals but it is not plotting the integrals obtained for different values of C .can u please help me to modify my code so that it plots :)



The Attempt at a Solution


This is my code that I have been working on:

% What are the integration limits?
clc
a = 2;
b =4;
% What is the integration step size?
dx = 0.1;
% An array containing the x points.
x = [a:dx:b];
% What is the function to integrate?
C=1:0.1:3;
C;
y =x.^3+tan(x)+C;
% The number of points
N = length(y);
%initialise the area variable
sum_y = 0;
%sum the interior elements of the y array
%note how the loop starts at 2 and stops at N-1
for I = 2:N-1
sum_y = sum_y + y(I);
area = dx*((y(1) + y(N))/2 + sum_y)

plot(area,C)
end

Thank you for your help:)
 
Physics news on Phys.org
Hi it seems to me that you have find area for different values of C. For every value of C, you have to integrate and find area, this needs outer 'for' loop. To plot the result the variable 'area' should be an array. I have modified your program slightly as given below.

clc
a = 2;
b =4;
% What is the integration step size?
dx = 0.1;
% An array containing the x points.
x = [a:dx:b];
% What is the function to integrate?
for C=1:0.1:3; % This loop to find area for different values of C
y =x.^3+tan(x)+C;
% The number of points
N = length(y);
%initialise the area variable
sum_y = 0;
%sum the interior elements of the y array
%note how the loop starts at 2 and stops at N-1
i=1; % index to store area in an array
for I = 2:N-1
sum_y = sum_y + y(I);
area (i)= dx*((y(1) + y(N))/2 + sum_y); % variable area is an array
i=i+1;
end
plot(area);
hold on % To plot areas for different values of C on same graph
end

Hope this helps
 
Thank you so much n.karthick :)
 

Similar threads

Replies
10
Views
2K
Replies
2
Views
2K
Replies
1
Views
2K
Replies
6
Views
2K
Replies
1
Views
2K
Replies
6
Views
2K
Replies
13
Views
3K
Replies
3
Views
2K
Back
Top