Content and rate of change in a buffer

2 views (last 30 days)
Ayda Baheri
Ayda Baheri on 7 May 2022
Answered: Mathieu NOE on 9 May 2022
this is a part of my code
I have a buffer and its content is changing according to the time and rates. I dont want Buffervalue to become zero so I want it to stay zero until the end of the time slot, when its ammount hits 0.
This is my code :
Time=[0.5 1 5 8 10 20 22 39 40 42 50 51 55 60 69 70 73 100 102 110];
Buff=0;
Buffervalue= zeros(1,10);
rate=[1 0.3 -16 2 -16 2 7 -16 -16 0.4 1 0.3 -16 2 -16 2 7 -16 -16 0.4];
for slot= 1:20
if Buff+(Time(slot)*rate(slot))<=0
Buffervalue(slot)=0;
else
Buff= Buff+(Time(slot)*rate(slot));
Buffervalue(slot)=Buff;
end
end
plot(Time,Buffervalue)
The problem is I have only one negative rate (-16) but when I look at the plot there are different slopes, so it kind of seems wrong to me.
Do you have any idea?

Answers (1)

Mathieu NOE
Mathieu NOE on 9 May 2022
hello
IMHO, the non uniform x spacing is prone to bug - so I prefered to resample the data with constant x spacing .
Now I wonder how the rate profile is supposed to evolve between "raw" values given in first place. a linear interpolation is my first guess but may not meet your initial goal
clc
clearvars
Time=[0.5 1 5 8 10 20 22 39 40 42 50 51 55 60 69 70 73 100 102 110];
Buff=0;
Buffervalue= 0;
rate=[1 0.3 -16 2 -16 2 7 -16 -16 0.4 1 0.3 -16 2 -16 2 7 -16 -16 0.4];
% resample data with fixed delta x spacing = 0.5
t = min(Time):0.5:max(Time);
rate_it = interp1(Time,rate,t);
for slot= 1:numel(t)
if Buff+(t(slot)*rate_it(slot))<=0
Buffervalue(slot)=0;
else
Buff= Buff+(t(slot)*rate_it(slot));
Buffervalue(slot)=Buff;
end
end
subplot(2,1,1),plot(Time,rate,'*b',t,rate_it,'r')
title(' Rate values');
legend('raw','interpolated');
subplot(2,1,2),plot(t,Buffervalue)
title(' Buffervalue ');

Categories

Find more on Variables in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!