Skip to main content

matlab-automation

Automate MATLAB operations including script execution, code evaluation, workspace management, Simulink modeling, and figure generation via COM and MCP interfaces. Use when user mentions MATLAB, matrix computation, numerical analysis, signal processing, Simulink, control system design, MATLAB自动化, 数值计算, 信号处理, 矩阵运算, Simulink建模, 控制系统.

Source facts

Repository
zunyiqingfeng-code/skills
Last source activity
August 21, 2026 at 14:34
Detected SKILL.md language
Chinese
Stars
2
Forks
0

Install options

The review-first prompt is selected by default. You can switch to a direct command or download a local copy.

Review the source files

Read SKILL.md and any companion files shown by SkillsMP before deciding whether to install.

File Explorer
2 files

Showing SKILL.md

SKILL.md
Source instructions · Read-only preview
name
matlab-automation
description
Automate MATLAB operations including script execution, code evaluation, workspace management, Simulink modeling, and figure generation via COM and MCP interfaces. Use when user mentions MATLAB, matrix computation, numerical analysis, signal processing, Simulink, control system design, MATLAB自动化, 数值计算, 信号处理, 矩阵运算, Simulink建模, 控制系统.
# MATLAB 自动化技能 ## 快速开始 ### 环境要求 - Windows 系统 + MATLAB R2024a 已安装 - Python 3.8+ + `pywin32` (`pip install pywin32`) - MATLAB 安装路径: `D:\Matlab` ### 连接 MATLAB ```python import sys sys.path.insert(0, r"C:\Users\曾金昌\.claude\skills\matlab-automation\scripts") from matlab_connect import connect_matlab, execute_command, run_script # 连接MATLAB matlab = connect_matlab() # 执行命令 result = execute_command(matlab, "disp('MATLAB COM接口工作正常!')") # 运行脚本 result = run_script(matlab, "script.m") ``` ## 核心工作流 ### 1. COM接口连接 ```python import win32com.client import pythoncom def connect_matlab(): """通过COM接口连接MATLAB""" pythoncom.CoInitialize() matlab = win32com.client.Dispatch("MATLAB.Application") return matlab def disconnect_matlab(matlab): """断开MATLAB连接""" matlab.Execute("quit") pythoncom.CoUninitialize() ``` ### 2. 命令执行 ```python def execute_command(matlab, command, silent=False): """执行MATLAB命令""" try: if not silent: print(f"[MATLAB] 执行: {command[:80]}...") result = matlab.Execute(command) if not silent and result.strip(): print(f"[MATLAB] 结果: {result[:200]}...") return {"success": True, "result": result} except Exception as e: return {"success": False, "error": str(e)} ``` ### 3. 脚本运行 ```python def run_script(matlab, script_path): """运行MATLAB脚本文件""" import os if not os.path.exists(script_path): return {"error": f"脚本文件不存在: {script_path}"} with open(script_path, 'r', encoding='utf-8') as f: script_content = f.read() return execute_command(matlab, script_content) ``` ## 使用示例 ### 示例1: 基本计算 ```python from matlab_connect import connect_matlab, execute_command matlab = connect_matlab() # 数学计算 execute_command(matlab, "x = 2 + 3 * 4; disp(['结果: ', num2str(x)])") # 矩阵操作 execute_command(matlab, "A = magic(3); disp('3x3魔方矩阵:'); disp(A)") # 函数计算 execute_command(matlab, "x = linspace(0, 2*pi, 100); y = sin(x); plot(x, y); title('正弦函数');") disconnect_matlab(matlab) ``` ### 示例2: Simulink建模 ```python from matlab_connect import connect_matlab, execute_command matlab = connect_matlab() # 打开Simulink execute_command(matlab, "simulink") # 创建简单模型 execute_command(matlab, """ new_system('test_model'); open_system('test_model'); % 添加模块 add_block('simulink/Sources/Sine Wave', 'test_model/Sine'); add_block('simulink/Sinks/Scope', 'test_model/Scope'); % 连接模块 add_line('test_model', 'Sine/1', 'Scope/1'); % 设置参数 set_param('test_model/Sine', 'Amplitude', '2'); set_param('test_model/Sine', 'Frequency', '1'); % 保存模型 save_system('test_model'); """) disconnect_matlab(matlab) ``` ### 示例3: 控制系统设计 ```python from matlab_connect import connect_matlab, execute_command matlab = connect_matlab() # 创建传递函数 execute_command(matlab, """ % 创建传递函数 num = [1]; den = [1, 2, 1]; sys = tf(num, den); % 显示传递函数 disp('传递函数:'); disp(sys); % 绘制阶跃响应 figure; step(sys); title('阶跃响应'); % 绘制波特图 figure; bode(sys); title('波特图'); % 计算稳定性 [GM, PM, Wcg, Wcp] = margin(sys); disp(['增益裕度: ', num2str(20*log10(GM)), ' dB']); disp(['相位裕度: ', num2str(PM), ' 度']); """) disconnect_matlab(matlab) ``` ## 高级功能 ### 1. 数据交换 ```python def save_to_mat(matlab, variable_name, data, filename='data.mat'): """保存数据到MAT文件""" # 在MATLAB中创建变量 execute_command(matlab, f"{variable_name} = {data};") # 保存到文件 execute_command(matlab, f"save('{filename}', '{variable_name}');") def load_from_mat(filename='data.mat'): """从MAT文件加载数据到Python""" import scipy.io data = scipy.io.loadmat(filename) return data ``` ### 2. 批量处理 ```python def batch_process(matlab, commands): """批量执行MATLAB命令""" results = [] for cmd in commands: result = execute_command(matlab, cmd) results.append(result) return results ``` ### 3. 错误处理 ```python def safe_execute(matlab, command): """安全执行命令,返回结果或错误信息""" try: return execute_command(matlab, command) except Exception as e: return { "success": False, "error": str(e), "command": command } ``` ## Simulink建模案例 ### 案例1: 弹簧-质量-阻尼系统 ```matlab % 创建弹簧-质量-阻尼系统模型 new_system('spring_mass_damper'); open_system('spring_mass_damper'); % 参数 m = 1; % 质量 (kg) k = 10; % 弹簧系数 (N/m) c = 0.5; % 阻尼系数 (Ns/m) % 添加模块 add_block('simulink/Continuous/Integrator', 'spring_mass_damper/Integrator1'); add_block('simulink/Continuous/Integrator', 'spring_mass_damper/Integrator2'); add_block('simulink/Math Operations/Gain', 'spring_mass_damper/Gain1'); add_block('simulink/Math Operations/Gain', 'spring_mass_damper/Gain2'); add_block('simulink/Math Operations/Sum', 'spring_mass_damper/Sum'); add_block('simulink/Sources/Step', 'spring_mass_damper/Step'); add_block('simulink/Sinks/Scope', 'spring_mass_damper/Scope'); % 设置增益 set_param('spring_mass_damper/Gain1', 'Gain', num2str(-k/m)); set_param('spring_mass_damper/Gain2', 'Gain', num2str(-c/m)); % 连接模块 add_line('spring_mass_damper', 'Step/1', 'Sum/1'); add_line('spring_mass_damper', 'Gain1/1', 'Sum/2'); add_line('spring_mass_damper', 'Gain2/1', 'Sum/3'); add_line('spring_mass_damper', 'Sum/1', 'Integrator1/1'); add_line('spring_mass_damper', 'Integrator1/1', 'Integrator2/1'); add_line('spring_mass_damper', 'Integrator2/1', 'Gain1/1'); add_line('spring_mass_damper', 'Integrator1/1', 'Gain2/1'); add_line('spring_mass_damper', 'Integrator2/1', 'Scope/1'); % 设置仿真参数 set_param('spring_mass_damper', 'StopTime', '10'); set_param('spring_mass_damper/Step', 'Time', '0'); set_param('spring_mass_damper/Step', 'Before', '0'); set_param('spring_mass_damper/Step', 'After', '1'); % 保存模型 save_system('spring_mass_damper'); ``` ### 案例2: PID控制器设计 ```matlab % 创建PID控制系统 new_system('pid_control'); open_system('pid_control'); % 添加模块 add_block('simulink/Sources/Step', 'pid_control/Reference'); add_block('simulink/Continuous/PID Controller', 'pid_control/PID'); add_block('simulink/Continuous/Transfer Fcn', 'pid_control/Plant'); add_block('simulink/Math Operations/Sum', 'pid_control/Sum'); add_block('simulink/Sinks/Scope', 'pid_control/Scope'); % 设置传递函数 (二阶系统) set_param('pid_control/Plant', 'Numerator', '[1]'); set_param('pid_control/Plant', 'Denominator', '[1, 2, 1]'); % 设置PID参数 set_param('pid_control/PID', 'P', '1.5'); set_param('pid_control/PID', 'I', '0.5'); set_param('pid_control/PID', 'D', '0.2'); % 连接模块 add_line('pid_control', 'Reference/1', 'Sum/1'); add_line('pid_control', 'Scope/1', 'Sum/2', 'autorouting', 'on'); add_line('pid_control', 'Sum/1', 'PID/1'); add_line('pid_control', 'PID/1', 'Plant/1'); add_line('pid_control', 'Plant/1', 'Scope/1'); % 设置仿真参数 set_param('pid_control', 'StopTime', '20'); % 保存模型 save_system('pid_control'); ``` ## 故障排除 ### 常见问题 1. **COM连接失败**: 确保MATLAB已安装且COM组件已注册 2. **命令执行错误**: 检查MATLAB语法,确保命令以分号结尾 3. **内存不足**: 定期清理MATLAB工作空间变量 4. **路径问题**: 确保MATLAB可执行文件路径正确 ### 调试技巧 ```python # 启用详细日志 def debug_execute(matlab, command): print(f"[DEBUG] 执行命令: {command}") result = execute_command(matlab, command, silent=False) print(f"[DEBUG] 结果: {result}") return result ``` ## 性能优化 1. **批量执行**: 将多个命令组合成脚本文件执行 2. **数据交换**: 使用MAT文件进行大数据传输 3. **内存管理**: 定期执行`clear`命令清理工作空间 4. **并行处理**: 复杂计算使用MATLAB的并行计算功能 ## 参考资料 - MATLAB官方文档: https://www.mathworks.com/help/matlab/ - Simulink文档: https://www.mathworks.com/help/simulink/ - Python win32com文档: https://pypi.org/project/pywin32/ --- **技能路径**: `C:\Users\曾金昌\.claude\skills\matlab-automation` **MATLAB路径**: `D:\Matlab` **创建时间**: 2026-04-20
View on GitHub