将所有 Simulink 手动开关状态导出为 JSON 的 Matlab 代码
此 MATLAB 函数遍历当前加载的 Simulink 模型(gcs)中的所有手动开关,并将其开关状态(0 或 1)导出为 JSON 字符串。
JSON 是直接生成的,而不是通过 struct() 和 jsonencode() 生成,因为 struct() 不支持字段名中的空格或斜杠。
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, '}'];
end示例输出
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