Reputation: 49
I am writing a function to find the definite integral of any function by using the Midpoint method, the output of this function must be a scalar value, where y(k+1)=dt*(f(t0+dt/2)+...+f(t(k)+dt/2)) this is the main idea of the Midpoint method and after calculating y(k+1) by using the for loop, it returns a scalar value of this integration, but I found that this function returns the output as a vector y which means it gives all values from y(1) to y(k+1). the exact value of this integration=14/3 which is very close to y(26) in the output vector. How can I get the output as a scalar value y(26) not a vector?
clear
//Midpoint integral
function [t,y]=Midpoint_Int(f,tinterval,n)
y=zeros(n+1,1); // preallocation of y
y(1)=0; //initial condition y(1)=y0=0
dt=(tinterval(2)-tinterval(1))/n;
t=tinterval(1):dt:tinterval(2);
for k=1:n
m2=f(t(k)+dt/2)
y(k+1)=y(k)+dt*m2;
end
t=t';
endfunction
function a=f(x)
a=1+x^2
endfunction
[t,y]=Midpoint_Int(f,[0,2],25)
Upvotes: 0
Views: 88
Reputation: 446
Just modify your function this way
function [t,y]=Midpoint_Int(f,tinterval,n)
y=0; //initial condition
dt=(tinterval(2)-tinterval(1))/n;
t=tinterval(1):dt:tinterval(2);
for k=1:n
m2=f(t(k)+dt/2)
y=y+dt*m2;
end
t=t';
endfunction
Upvotes: 1