Trapezoid Rule discrete data input

3 visualizaciones (últimos 30 días)
student
student el 24 de Nov. de 2019
Comentada: Kaashyap Pappu el 28 de Nov. de 2019
function[I]=trap(f,a,b)
if numel(f)>1
n=numel(f);
h=(b-a)/(n-1);
I=(h/2)*(f(1)+2*sum(f(2:end-1))+f(end));
elseif numel(f)==1
n=100;
h=(b-a)/(n-1);
x=a:h:b;
I=(h/2)*(f(x(1))+2*sum(f(x(2:end-1)))+f(x(end)));
end
This is the code I have so far. I am trying to create a function to approximate an integral based on the trapezoid rule that can take in either an array or an anonymous function. F is the anonymous function or array, and a and b are the bounds of the integral. I am not sure how to index the trapezoid equation (line 6) when the input is an array and I am given values for x and f(x).
  4 comentarios
Jan
Jan el 25 de Nov. de 2019
@student: I do not understand, what you are confused about. The show code is working already, isn't it? The values of a and b matter only for the determination of h. You do not need to do anything to let "x values correspond to their f(x) values". f(1) is the fist element of the vector and the value of a has no effect for the calculations.
Hint:
if isnumeric(f)
...
else
...
end
is enough. Alternatively:
if isnumeric(f)
...
elseif isa(f, 'function_handle')
...
else
error('1st input must be a vector or function handle.')
end
Kaashyap Pappu
Kaashyap Pappu el 28 de Nov. de 2019
The values of ‘a’ and ‘b’ are useful if the intervals are unevenly spaced. Otherwise as mentioned, this should run correctly.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by