# error : Function integration trapezoidal

6 visualizzazioni (ultimi 30 giorni)
jakv il 3 Dic 2013
Commentato: Sam il 14 Apr 2023
i want to calculate area from numerical integration of function f(x) with the limits a to b and vary n . by the way i use this code from my handbook, numerical chapra. to solve my problem. but the result was error.
function I = trap(func,a,b,n,varargin)
% trap: composite trapezoidal rule quadrature
% I = trap(func,a,b,n,p1,p2,...):
% composite trapezoidal rule
% input:
% func = name of function to be integrated
% a, b = integration limits
% n = number of segments (default = 100)
% p1,p2,... = additional parameters used by func
% output:
% I = integral estimate
if nargin<3,error('at least 3 input arguments required'),end
if ~(b>a),error('upper bound must be greater than lower'),end
if nargin<4|isempty(n),n=100;end
x = a; h = (b - a)/n;
s=func(a,varargin{:});
for i = 1 : n-1
x = x + h;
s = s + 2*func(x,varargin{:});
end
s = s + func(b,varargin{:});
I = (b - a) * s/(2*n);
the error :
??? function I = trap(func,a,b,n,varargin)
|
Error: Function definitions are not permitted in this context.
what should i do ?
--- my purpose is to make the table like below this text, to known how the error result with vary n parameter.
%
##### 2 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
jakv il 3 Dic 2013
what the script that i can use ? sorry i'm newbie.

Accedi per commentare.

### Risposta accettata

sixwwwwww il 4 Dic 2013
These links shows how to use matlab functions. and how to input and get output values from them
##### 4 CommentiMostra 3 commenti meno recentiNascondi 3 commenti meno recenti
Sam il 14 Apr 2023
Changing the 2 "l"s ("L"s; Capital shown for variable clarity) to a "1" ("One") in the line of the For loop fixes the error and allows the same anser to be attained as shown in the textbook (1.5948).

Accedi per commentare.

### Più risposte (1)

Torsten il 20 Mag 2016
Modificato: Torsten il 20 Mag 2016
My guess is that the "l" in the formula
s = s+(x(k+l)-x(k))*(y(k)+y(k+l))/2;
should be a "1".
Best wishes
Torsten.
##### 1 CommentoMostra NessunoNascondi Nessuno
Sam il 14 Apr 2023
Yes this appears to be correct, @Torsten.

Accedi per commentare.

### Categorie

Scopri di più su Startup and Shutdown in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by