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.
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:
Thank you for your reply. My current solution aligns with your answer. I actually figured out how to use Dictionary in MATLAB function block. The key is to use coder.extrinsic and include all Dictionary functions you need. For example,
To note, not every keytype of Dictionary is supported in code generation even using coder.extrinsic. For example, if you declare d = configureDictionary("string", "double), you will encounter an error. so far, I only tried "double" to "double". Hope this function can be extended in the future.
Da Änderungen an der Seite vorgenommen wurden, kann diese Aktion nicht abgeschlossen werden. Laden Sie die Seite neu, um sie im aktualisierten Zustand anzuzeigen.
Translated by
Website auswählen
Wählen Sie eine Website aus, um übersetzte Inhalte (sofern verfügbar) sowie lokale Veranstaltungen und Angebote anzuzeigen. Auf der Grundlage Ihres Standorts empfehlen wir Ihnen die folgende Auswahl: .
Sie können auch eine Website aus der folgenden Liste auswählen:
So erhalten Sie die bestmögliche Leistung auf der Website
Wählen Sie für die bestmögliche Website-Leistung die Website für China (auf Chinesisch oder Englisch). Andere landesspezifische Websites von MathWorks sind für Besuche von Ihrem Standort aus nicht optimiert.