trapezoidal rule with user define function

I am new in matlab.i want to create user define function for trapezoidal rule in which i want to take input arguments a,b,n, and the intervals values.I have seached alot but all function taking a function in argument not interval values..

3 个评论

John - please describe in detail the function that you want to create. What should the function signature be? Are you using trapz or implementing your own function for the trapezoidal rule? Are the input arguments just a, b, and n where presumably n will be used to determine the number of elements that you will take from the interval [a,b]. What does all function taking a function in argument not interval values mean? Which function takes a function as an input (?) argument?
I want to take interval values such as x=[0 2 4 6 8] and f(x)=[3 7 11 9 3], i dont want to use function f to calculate the trapezoidal in user define function. I want to take x and y as input in function with variable a,b and n
function r = trapezoidal(f, a, b, n)
% TRAPEZOIDAL Numerical integration from a to b
% with n intervals by the Trapezoidal rule
h = (b-a)/n;
s = 0.5*(f(a) + f(b));
for i = 1:n-1
s = s + f(a+i*h);
end
r = h*s;
Output:
>> f = @(x)sin(x);
>> I1 = trapezoidal( f, 0, pi/2, 1 )
I1 =
0.785398163397448
But this seems not to make any sense at all.
You want to pass in the actual vectors x and y? If so, then it makes no sense to also pass in a, b, and n. If you already have x as a vector, then x is given. If you already have y as a vector, then f as a function is irrelevant.
Are you asking how to write the trapezoidal rule for VECTORS x and y as already given?
I would note there is absolutely no reason to do this, since you already have the function trapz which does exactly that. trapz is part of MATLAB already. So unless this is your homework assignment, then there is no need.
So what would the function header look like? Start out one line at a time.

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by