MATLAB: Find where the gradient in a line is less than 0.001

graphMATLAB

hello there
I am trying to find the position on the graph where the line stabilises sort of, as in where the gradient is close to 0 and stays close to 0.
this is my code ATM:
%% Cleaning crew
clc
clear
clc
%% X values
%x = linspace(0,6);
x = [0:0.1:6];
%% equation
y = 1 - (1.18*exp(-3.4766*x)) + (0.17*exp(-0.5166*x));
%% Find peak
[PKy, PKx] = findpeaks(y,x)
%% plot graph
plot(x,y);
hold on
yline(1);
hold on
%%
B = gradient(y)
Thank you in advance.

Best Answer

I think you want to find where the signal levels out and becomes fairly assymptotic and flat. I don't think you just want to find where the slope is perfectly flat, which of course would be at the peak. So take the derivative and look where the value gets close enough to zero for your liking. Try this:
clc; % Clear the command window.
fprintf('Beginning to run %s.m.\n', mfilename);
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
%% X values
%x = linspace(0,6);
x = [0:0.1:6];
% equation y = a1 + a2 * exp(a3 * x) + a4 * exp(a5 * x)
% derivative: dy = a2 * a3 * exp(a3 * x) + a4 * a5 * exp(a5 * x)
y = 1 - (1.18*exp(-3.4766*x)) + (0.17*exp(-0.5166*x));
a = [1, -1.18, -3.4766, 0.17, -0.5166]
% Set dy = 0 = a2 * a3 * exp(a3 * x) + a4 * a5 * exp(a5 * x)
dy = a(2) * a(3) * exp(a(3) * x) + a(4) * a(5) * exp(a(5) * x)
% -a2*a3 * exp(a3*x) = a4*a5*exp(a5*x)
% exp((a3-a5)*x) = -(a4*a5) / (a2 * a3)
% (a3-a5)*x = log(-(a4*a5) / (a2 * a3))
% Solving fox x = log(-(a4*a5) / (a2 * a3)) / (a3-a5)
xPeak = log(-(a(4) * a(5)) / (a(2) * a(3))) / (a(3)-a(5))
% Find peak
[PKy, PKx] = findpeaks(y,x)
% plot graph
subplot(1, 2, 1);
plot(x, y, 'b-', 'LineWidth', 2);
hold on
xline(xPeak, 'Color', 'r', 'LineWidth', 2);
grid on;
title('Original y', 'FontSize', 15);
caption = sprintf(' Slope exactly flat at x=%.3f', xPeak);
text(xPeak, 0.5, caption, 'Color', 'r', 'FontWeight', 'bold');
% Plot gradient (slope)
subplot(1, 2, 2);
plot(x,dy, 'b-', 'LineWidth', 2);
title('Derivative of y', 'FontSize', 15);
hold on
grid on;
xline(xPeak, 'Color', 'r', 'LineWidth', 2);
caption = sprintf(' Slope exactly flat at x=%.3f', xPeak);
text(xPeak, 2.25, caption, 'Color', 'r', 'FontWeight', 'bold');
% Find the last place where the slope is more negative that 0.025
% or whatever value you decide is flat enough.
plot(x, dy, 'b-', 'LineWidth', 2);
index = find(dy < -0.025, 1, 'last');
xSlope = x(index)
xline(xSlope, 'Color', 'r', 'LineWidth', 2);
caption = sprintf(' Slope fairly flat after x=%.3f', xSlope);
text(xSlope, 0.25, caption, 'Color', 'r', 'FontWeight', 'bold');