How to code a time delay specified by a value saved in a parameter structure in a Matlab block?
31 views (last 30 days)
Show older comments
Hi,
I'm having an issue trying to go about coding a time delay within a matlab block.
Say I have a matlab block function for basic mass balance, such as:
function [X1,Y1] = fcn(Z1)
% Set transfer function value(s).
A1 = 0.8;
% Calculate the products.
X1 = Z1*A1;
Y1 = Z1*(1-A1);
end
But I need the outputs [X1,Y1] to be delayed by a certain length of time (NOT paused) specified by a value in a parameter structure in the base workspace, such as:
% Example parameter structure index for time delay value.
myParams.dt(1) = 24.8
I've been looking into other feeds for using persistent variables, but my Matlab skills are not yet very advanced. This needs to be coded in for my purposes and not looking to use a predefined simulink block (e.g. transport delay, triggered subsystems, etc.).
Could someone please help me with this seemingly simple piece of code?
Thanks so much in advance!
Cheers,
0 Comments
Answers (1)
Fangjun Jiang
on 13 Apr 2022
In the MATLAB Function block editor, click the "edit data" button, then add parameter. Define the "myParams" in base workspace as the parameter of the MATLAB Function block and then you will be able to use it. I am not sure if a structure has anything special, you could try a regular variable first.
5 Comments
Fangjun Jiang
on 13 Apr 2022
The code in the comment looks right. But it is only one step delay (the delay time is the same as the simulation step).
If you want to delay for arbitrary time, you need to calculate N=DelayTime/SimulationStepTime before the simulation in your initilization routine. Then in the code, something like this:
if isempty(u_d)
u_d=zeros(1,N);
end
% shift the buffer, there might be better way than using for-loop
for k=N:-1:2
u_d(k)=u_d(k-1);
end
% take the current input
u_d(1)=u;
y=u_d(k);
See Also
Categories
Find more on Event Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!