Matlab-Code, um alle Simulink-Manual-Switch-Zustände als JSON zu exportieren
Diese MATLAB-Funktion iteriert durch alle Manual-Switches im aktuell geladenen Simulink-Modell (gcs) und exportiert deren Schaltzustand (0 oder 1) in einen JSON-String.
Das JSON wird direkt generiert und nicht über struct() und jsonencode(), da struct() keine Leerzeichen oder Schrägstriche in Feldnamen unterstützt.
switch_positions_to_json.m
function jsonStr = switch_positions_to_json()
% Finds all Switches in the Simulink model
switches = find_system(gcs, 'BlockType', 'ManualSwitch');
% Initializes a JSON string with an opening curly brace
jsonStr = '{';
% Iterates through all switches
for i = 1:length(switches)
switchPath = switches{i};
switchPos = get_param(switchPath, 'sw');
% Adds key-value pair to the JSON string
if i > 1
jsonStr = [jsonStr, ','];
end
% Replace newlines in the switch path with escaped backslash + n
escapedSwitchPath = strrep(switchPath, newline, '\\n');
% Adds the key in quotes and the value
jsonStr = [jsonStr, '"', escapedSwitchPath, '":', switchPos];
end
% Closes the JSON string with a closing curly brace
jsonStr = [jsonStr, '}'];
endBeispiel-Ausgabe
switch_positions_example.json
{"MySimulinkModel/Manual Switch":0,"MySimulinkModel/Subsystem/Null switch":1}Check out similar posts by category:
Matlab/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow