Using embedded function block to find differential

1 回表示 (過去 30 日間)
Amir Khan
Amir Khan 2012 年 7 月 12 日
Hello,
I have a signal and I want to write a code in embedded matlab function block, which could take signal value at the next time step and subtract previous value from it, but the first value has to be zero always. For example, consider the following data with "B" as the main signal, and "dB" would be my required result:
B= 1 3 7 9 11 12
dB= 0 (3-1) (7-3) (9-7) (11-9) (12-11) = 0 2 4 2 2 1
I have written a code to achieve this which is as follows:
  1. function dB=fcn (B)
  2. persistent Bprev;
  3. if isempty (Bprev)
  4. Bprev=B;
  5. end
  6. dB=B-Bprev;
The results from this function, for the same values of B are as follows: # B=1 3 7 9 11 12 # dB= 0 2 6 8 10 11
I think my code is retaining all the previous dB values and adding them to the next dB values. i.e dB= Bnext-Bprev+dBprev, whereas I only want the function to do like this dB= 0 (first value) and then Bnext-Bprev
Can somebody help me in sorting this out.. Will greatly appreciate any help! Thanks

採用された回答

TAB
TAB 2012 年 7 月 12 日
編集済み: TAB 2012 年 7 月 12 日
As per your requirement
function dB=fcn(B)
persistent Bprev;
if isempty (Bprev)
Bprev = B;
dB = 0;
else
dB = B-Bprev;
Bprev = B; % Save current value to use it as previous in next sample time.
end
  1 件のコメント
Amir Khan
Amir Khan 2012 年 7 月 12 日
Thanks TAB, its working perfectly!! Really appreciate your help!!

サインインしてコメントする。

その他の回答 (0 件)

Community Treasure Hunt

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

Start Hunting!

Translated by