function [m, x, p] = interpcurves(c)
%
% This function reads in a cell array C, which are point extracted from a
% Curve Tracer output using function GETCURVES. GETCURVES creates a cell
% array from CSV files obtained from the TI B370 Curve tracer output.
% Column 1 is the x-axis of the curve tracer (trimmed voltage sweep values),
% column 2 is the corresponding current values, and for cases where there was
% a stepping parameters (i.e. base current or gate-source voltage) column 3
% would be the step sequence values.
%
% [m, x, p] = interpcurves(c)
%
% M is the TC curve matrix where all rows are the same lengght and sampled
% as the same rate corresponding the x-axis X. The rows are the curves
% corresponding to each step value. In the case of just a single
% sweep, as in a diode, M will just have one row.
% The output is P will exist if there were step values originally provided
% with the curve trace data. Otherwise for a single sweep, no P vector
% will be created.
%
% Written by Kevin D. Donohue 5/2005 donohue@engr.uky.edu
%
% Check out the size of the cell array and set interpolation
% range to the smallest end point in all the cell array rows.
[r,g] = size(c);
for k=1:r
lim1(k) = max(c{k,1});
end
% Take the shortest sweep as the lenght of x-axis
toplim = min(lim1);
% Create x-axis with 100 points
pts = 100; % Change this value if you want output sampling density to change
x = toplim*[0:(pts-1)]/(pts-1);
% If a 3 terminal device save the stepped values to output vector
if g == 3
p = cell2mat(c(:,3));
end
% Loop to extract vectors from cell array and make them equally
% spaced and sized to store as a matrix
for k=1:r
da = cell2mat(c(k,1)); % Convert cell to row matrix
ya = cell2mat(c(k,2));
gg = gradient(da); % Get gradient of row x-axis
% Ensure there are no place where the x-axis was not changing
ksame = find(abs(gg) > eps);
% If a range of non-changing values were found, trim them
if ~isempty(ksame)
yt = ya(ksame);
dt = da(ksame);
else
yt = ya;
dt = da;
end
% Double check for monotonicity. X-axis must be strictly increase or decreasing.
% If not monotonic drop deviant point
gg = diff(dt); % Get consecutive differences
y(1) = yt(1); % Initialze first point
d(1) = dt(1);
cnt=1; % Set up counter for final output array
for kd=2:length(dt)-1
if (dt(kd)-d(cnt))*gg(kd) > 0 % If differences has same sign store the value
cnt = cnt+1;
d(cnt) = dt(kd);
y(cnt) = yt(kd);
else % If not, skip the values and reset the sign.
gg(kd) = -gg(kd);
end
end
% last point cannot be checked so skip it (ie. to end-1)
% Interpolate Curve trace values to regular sample grid
m(k,:) = interp1(d(1:end-1),y(1:end-1),x,'linear', 'extrap');
end