Real-time Numerical differentiation in MATLAB function block

조회 수: 5 (최근 30일)
Femi Bolarinwa
Femi Bolarinwa 2020년 11월 26일
댓글: Femi Bolarinwa 2020년 11월 26일
I'm trying to build a matlab function block execute a real time numerical derivative of a signal using persistent variable as a form of memory to store the previous data point. I have something like this:
function dth2 = fcn(th2)
sampt = 0.1;
persistent i
persistent dth
persistent reg_th2
if isempty(i)
i = 1;
dth = zeros(4,1); %register to store output dth2
reg_th2 = zeros(4,1); %register to store input th2
end
reg_th2(i,1) = th2;
dth(i) = (reg_th2(i+1,1) - reg_th2(i-1,1))/(2*sampt); %error keeps poping up here: Index value 5 exceeds valid range [1-4] for array 'reg_th2'
i = i + 1;
reg_th2 = [reg_th2(2:end); reg_th2(i,1)];
dth2 = dth(end);
Ps: i'm trying to build an alternative to the standard 'Discrete Derivative' simulink block
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 11월 26일
What are you expecting to have happen on the 4th invocation when reg_th2(i+1,1) would be outside of the range of the zeros(4,1) that you initialized reg_th2 to ?

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2020년 11월 26일
ioff = min(3, i);
reg_th2(ioff,1) = th2;
dth(ioff) = (reg_th2(ioff+1,1) - reg_th2(ioff-1,1))/(2*sampt);
i = i + 1;
dth2 = dth(ioff);
However it then becomes unclear why you would have a memory 4 deep when you only use 3 deep (value before, value, value after) ?
  댓글 수: 1
Femi Bolarinwa
Femi Bolarinwa 2020년 11월 26일
i thought since my counter i starts from 2, i'd need one more space. Thanks, this runs in simulink but dth2 doesnt appear to be the derivative of th2

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programmatic Model Editing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by