I need to code a function with two inputs (x,Tau)
. Let's suppose that the vector is a simple x=sin(t)
. The function must detect the local maximum. If a local max is spotted, it should deteriorate from there with the exp(-t/Tau)
until the sin(x)
is greater again. From there, the x
should be followed until the next local max. It is a kind of a low pass filter, but I cannot code it properly in Octave.
Here is a sample picture drawn by hand:
This question is more mathematics than computing. The following solution will work when your first curve is a smooth function, but I'm not sure how well it would work if your input is a set of experimentally measured values with a high degree of scatter. In that case you might need something more sophisticated.
I assume you want to make the decay curve deviate from the underlying curve not at the maximum but at the point slightly past the maximum where the downward slope of the underlying curve first exceeds that of exponential decay with time constant tau. This seems like a much more physical situation. Switching to exponential decay at the literal maximum could/would result in the decay curve actually crossing the underlying curve.
If your 'sine' function is x(t), and if the decay constant is tau, then you need a new symbol for the red curve in your graph. Call this y(t). Representing the time axis by a vector of numbers t = [t(1), t(2), ..., t(n)] and the corresponding values of your 'sine' function by a vector x = [x(1), x(2), ..., x(n)] and setting y(1) = x(1), then the (i > 1)th member of the vector y is given by max(x(i), y(i-1) exp(-(t(i) - t(i-1))/tau)).
Implementing this in Octave is straightforward:
clear
t = linspace(0, 6*pi, 1000); %Or whatever
x = sin(t); %Could be any function
function y = decay(x, t, tau)
y = zeros(1, length(t));
y(1) = x(1);
for i = 2:length(t)
y(i) = max(x(i), y(i-1)*exp(-(t(i)-t(i-1))/tau));
endfor
endfunction
tau = 10;
y = decay(x, t, tau);
clf
hold on
plot(t, x)
plot(t, y)
hold off
If you want to use the above function regularly it would probably be a good idea to add checks to make sure that the correct number of arguments are passed, that x and t are the same length and that tau is a scalar.