Q:

Area under curve cyclic voltammetry within specific bound

I want to calculate the integral area under the curve for I>0 and V<0.4, I could not do it with trapz function, please help!
I have tried both integral and trapz functions but of no use! I could not attach the text file so if you need it for debugging, please let me know how to do that.
close all
clear all
clc
c=Constants;
F = dir('*.txt');  
nF = length(F) ;
count = 0 ;
for ii = 1:nF
fname = F(ii).name ;
end
filename = fullfile(fname);
fileID = fopen(filename);
formatSpec = '%s';
N = 1;
c_text = textscan(fileID,formatSpec,N,'Delimiter',' ');
c_data = textscan(fileID,'%f %f');
v=c_data{1};
i=c_data{2};

idi = i>0;
idv=v<0.4;
v_pos = v(idv);
i_pos= i(idi); 
% v_limit=v_pos(idv)

inty = trapz(v_pos, i_pos)

setvalue = 0.06;
[~,closestIndex] = min(abs(setvalue-v_pos));
vm= v_pos(closestIndex)

setvalue = 0.4;
[~,closestIndex] = min(abs(setvalue-v_pos));
vf= v_pos(closestIndex)
ifinal=i_pos(closestIndex)

figure(1)
plot(v,i)
hold on
hold off
grid
area=inty-[(vf-vm)*ifinal]
yline(0);

cvarea=area/1000;
qh=cvarea/c.cvscanrate;
active_area=qh/(c.qpt*c.A);
fprintf('Active surface area of catalyst %g cm^2 Pt/ cm^2 electrode \n', active_area);

Error using trapz (line 66)
Point spacing must be a scalar specifying uniform spacing or a vector of x-coordinates for each data point.

A:

There is several method to compute a discret integral.
Here is the Riemann sum approximation

And here is the trapezoidal rule used by trapz

The Riemann sum is the easiest to compute.
You simply need the width and the height of each rectangle (so we can calculate the area).
%Dummy data:
x = 0:0.1:10;
y = x.^2;  
%Width
X = diff(x)
%Height
Y = conv(y,ones(2,1),'valid')/2
%Integral:
I = sum(X.*Y)

This method would work even if the point spacing are not uniform.

