Question

How do I implement the diff() function available in Matlab using Simulink block?

I need to read a sequence of digital sensor data (x,y) where, x=[0, 5, 10, 15, 20, 25, 30, ... 100]. I want to calculate the change in x i.e. del_x. My assumption is that since it is a sequence of data, I can assume time as unit time t=[0, 1, 2, 3, 4, 5, 6, 7, ... 20].

Now I tried this simple model in Simulink with Model Configuration Parameters being:

Start time: 0.0
Stop time: 20
Solver Option = Fixed-step
Solver: discrete (no continuous states)
Fixed-step size (fundamental sample time): 1

Simple Discrete Derivative test in Simulink

Here, simin is equal to the input array x as described above. But simout becomes del_x = [5, 10, 15, 20, 25, 30, 35 ... 100]. So my question is, shouldn't the change in x (or simout) be del_x = [0, 5, 5, 5, 5, 5, 5, 5, ... ] since the change in x is always changing constantly by 5? In Matlab, diff() function gives me the desired result.

Using the equation: del_x = (x[i] - x[i-1])/(t[i]-t[i-1]) = (x[i] - x[i-1])/(1)

Why is the output the delayed version x[t-1] of the input x[t] instead of change in x? Isn't the Discrete Derivative block supposed to operate identical to diff() function in Matlab? Also the Difference block gives the same undesired result. Just for bigger picture sake, I need to export a larger version of the Simulink model into C++ code in order to get the error and change in error of the sensor in order to implement a closed-loop control system but this simple simulation doesn't give the result I want.

UPDATE: It works with Matlab Function block with diff() inside. But Simulink needs to go through a long compilation stage just to implement it. Isn't there something simple that I am missing here?

Matlab function block implementation of diff() function

UPDATE2: All sample times are the same i.e. 1 (Display->Sample Time->All option).

enter image description here

Was it helpful?

Solution

You should set your source (From Workspace) to output one sample per time instant. Currently I think all of your data is going out at the same instant. Your simin in "From workspace" should be similar to the following struct for your case.

simin.time = 0:20;
simin.signals.values = (0:5:100)';
simin.signals.dimensions = 1;

Now if you set your sample time to 1 and run your model for 20 steps then you should get your desired output.

For this data your code in MATLAB Function will not do what you want. You need to implement the diff with a persistent variable to match other blocks with delay.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top