MATLAB: Hello! I need to split a curve each time it reaches a certain x-value. Is it possible

data analysisMATLABsignal processing

Best Answer

In this example I plot a sine curve, find the index values of the peaks, and I extract the line segments that connect the peaks.
segmentsX and segmentsY are cell arrays containing the segments.
% Fake data
x = 0:.1:30;
y = sin(x);
plot(x,y, '-b');
hold on
% Find peaks
% locs is a vector of index values of y where y peaks.
[~,locs] = findpeaks(y);
% Extract peak-to-peak segments
startEndIdx = [locs(1:end-1);locs(2:end)]; %[start; end]
segmentsX = cell(size(startEndIdx,2));
segmentsY = segmentsX;
for i = 1:size(startEndIdx,2)
segmentsX{i} = x(startEndIdx(1,i):startEndIdx(2,i));
segmentsY{i} = y(startEndIdx(1,i):startEndIdx(2,i));
end
% add 1 segment to the plot to confirm it worked
plot(segmentsX{1}, segmentsY{1}, ':b', 'LineWidth', 4)