Globalize a Dictionary or containers.Maps and use it in MATLAB function block in Simulink?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Chang-Mu
am 5 Dez. 2023
Kommentiert: Chang-Mu
am 14 Dez. 2023
Hello MATLAB community,
I was attempting to use a hashtable as global variable in MATLAB function block in Simulink for checking whether an ID has appeared before. However, it seems like Simulink currently doesn't support Dictionary. So, I was wondering if anyone tried this before and can suggest other approaches.
Thank you.
0 Kommentare
Akzeptierte Antwort
Pratyush Swain
am 14 Dez. 2023
Hi Chang-Mu,
To achieve your goal of checking for new and redundant IDs in a MATLAB function block within Simulink, we can use "persistent" variables as a workaround.
Here's an example Simulink model. I've used "persistent" variables in a MATLAB function block to check for ID redundancy. The input "u" is a binary input (0/1) generated by a combination of "Sine Wave" and "Sign" blocks. The function block returns true for a new ID and false for a redundant ID.
Next we can create the function block in the following manner:
function y = processID(id)
% Declare the persistent variable to store the list of IDs
persistent idList;
persistent index;
% Initialize the list if it's empty %
if isempty(idList)
% Preallocate size based on time duration of simulation %
idList = zeros(1,20);
index=1;
end
% Check if the ID exists in the list %
if ~any(idList == id)
% If the ID doesn't exist, add it to the list and return 1 %
idList(index) = id;
y = 1;
% Update index %
index=index+1;
else
% ID already exists , return 0 %
y = 0;
end
end
Finally the output of the simulation can be realized as follows:
This implementation is based on the example at https://www.mathworks.com/help/simulink/ug/initialize-persistent-variables.html. Please ensure you follow the guidelines in the link before running the model, especially the "Allow direct feedthrough" property of the MATLAB function block. You can find instructions for setting block properties at https://www.mathworks.com/help/simulink/ug/matlab-function-block-properties.html.
For more information on persistent variables and other Simulink data store alternatives, please refer to:
I've also attached the Simulink model for your reference.
Hope this helps.
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Event Functions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!