Matlab 输出变量值使用 fprintf("%d.....", variable)

博客介绍了在Matlab中输出变量值的方法,即使用fprintf函数,具体格式为fprintf(\%d…\ variable)。

Matlab 输出变量值使用 fprintf("%d…", variable)

%% 天线桁架优化主函数(ANSYS调用修复版) function [x_opt, fval, optimHistory] = truss_optimization() % 1. 基础配置(重点修正ANSYS路径) config = struct(); % 设计变量配置 config.DesignVars = {'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7'}; config.x0 = ones(1, 7); config.lb = 0.5 * ones(1, 7); config.ub = 2.0 * ones(1, 7); % 关键:修正ANSYS路径(必须是求解器路径,无多余符号) config.AnsysExe = 'C:\Program Files\ANSYS Inc\v241\ANSYS\bin\winx64\launcher.exe'; % 去掉外层双引号,后续统一处理 config.StressLimit = 156.67e6; config.DispLimit = 0.0001; config.MaxRetry = 3; config.Timeout = 600; % 路径配置(确保无中文/特殊字符) mainDir = fileparts(mfilename('fullpath')); config.WorkDir = fullfile(mainDir, 'ANSYS_Work'); config.TemplateDir = fullfile(mainDir, 'APDL_Templates'); config.ApdlTemplate = fullfile(config.TemplateDir, 'optim_template.apdl.txt'); config.ResultFile = fullfile(config.WorkDir, 'results.txt'); config.AnsysLog = fullfile(config.WorkDir, 'ANSYS_Run.log'); config.OptLog = fullfile(config.WorkDir, 'Optimization_History.csv'); config.ReportFile = fullfile(mainDir, 'Optimization_Result_Report.txt'); % 2. 前置初始化与校验 try % 2.1 创建目录(无中文路径) if ~exist(config.WorkDir, 'dir') mkdir(config.WorkDir); fprintf('✅ 创建工作目录:%s\n', config.WorkDir); end if ~exist(config.TemplateDir, 'dir') mkdir(config.TemplateDir); fprintf('✅ 创建模板目录:%s\n', config.TemplateDir); end % 2.2 校验APDL模板 if ~isfile(config.ApdlTemplate) error('APDL模板缺失!请放入:%s', config.ApdlTemplate); end fprintf('✅ 找到APDL模板:%s\n', config.ApdlTemplate); % 2.3 校验ANSYS路径(关键!) if ~isfile(config.AnsysExe) error('ANSYS求解器不存在!路径:%s\n请确认安装路径', config.AnsysExe); end fprintf('✅ 找到ANSYS求解器:%s\n', config.AnsysExe); % 2.4 初始化优化日志 fid = fopen(config.OptLog, 'w'); fprintf(fid, '迭代次数,质量(kg),a1,a2,a3,a4,a5,a6,a7,关键点1Z位移(m),关键点2Z位移(m),关键点3Z位移(m),最大应力(Pa)\n'); fclose(fid); catch ME error('初始化失败:%s', ME.message); end % 3. 初始点验证(优先解决此步) fprintf('\n=== 初始点验证 ===\n'); [initMass, initC, initRes, initSucc] = eval_design(config.x0, config); if ~initSucc error('初始点计算失败!请先解决ANSYS调用问题(查看日志:%s)', config.AnsysLog); end fprintf('✅ 初始点验证通过:质量=%.4f kg,最大应力=%.2f MPa\n', initMass, initRes.maxStress/1e6); % 4. 优化算法配置 options = optimoptions('fmincon', ... 'Display', 'iter', ... 'Algorithm', 'sqp', ... 'MaxIterations', 50, ... 'ConstraintTolerance', 1e-6, ... 'PlotFcn', @optimplotfval); % 5. 执行优化 fprintf('\n=== 启动优化 ===\n'); [x_opt, fval, exitflag, output] = fmincon(... @(x) obj_fun(x, config), ... config.x0, [], [], [], [], ... config.lb, config.ub, [], options); % 6. 结果输出 [optMass, optC, optRes, optSucc] = eval_design(x_opt, config); generate_report(config, x_opt, initMass, initRes, optMass, optRes, exitflag, output); optimHistory = readtable(config.OptLog); fprintf('\n=== 优化完成 ===\n'); fprintf('最优设计变量:a1=%.4f,a2=%.4f,a3=%.4f,a4=%.4f,a5=%.4f,a6=%.4f,a7=%.4f\n', x_opt); fprintf('最小质量:%.4f kg(优化率:%.2f%%)\n', optMass, (initMass-optMass)/initMass*100); end % -------------------------- 核心辅助函数:评估设计点(修复ANSYS调用) -------------------------- function [mass, c, res, success] = eval_design(x, config) success = false; mass = inf; c = [inf; inf]; res = struct('maxStress', 0, 'uz1', 0, 'uz2', 0, 'uz3', 0, 'gravity', 0); try % 1. 生成临时APDL(无特殊字符) tempApdl = fullfile(config.WorkDir, sprintf('Temp_APDL_%s.apdl', datestr(now, 'HHMMSSFFF'))); fid = fopen(config.ApdlTemplate, 'r'); apdl = fread(fid, '*char')'; fclose(fid); % 替换a1-a7 for i = 1:7 apdl = regexprep(apdl, sprintf('a%d=1', i), sprintf('a%d=%.6f', i, x(i))); end fwrite(fopen(tempApdl, 'w'), apdl); % 2. 调用ANSYS(去掉-noshell,改用兼容格式) ansysCmd = sprintf('"%s" -b -i "%s" -o "%s"', ... config.AnsysExe, tempApdl, config.AnsysLog); % 直接执行命令(兼容所有MATLAB版本) [runStatus, cmdOut] = system(ansysCmd, config.Timeout); if runStatus ~= 0 error('ANSYS执行失败:状态码=%d输出=%s', runStatus, cmdOut); end % 3. 读取结果 if ~isfile(config.ResultFile) error('ANSYS未生成结果文件:%s', config.ResultFile); end data = load(config.ResultFile); res.maxStress = data(1,1); res.gravity = data(1,3); res.uz1 = data(1,4); res.uz2 = data(1,5); res.uz3 = data(1,6); % 4. 计算目标函数与约束 mass = res.gravity / 9.81; dispRMS = sqrt((res.uz1^2 + res.uz2^2 + res.uz3^2)/3); c(1) = res.maxStress - config.StressLimit; c(2) = dispRMS - config.DispLimit; success = true; delete(tempApdl); catch ME fprintf(2, '❌ 设计点失败:%s\n', ME.message); fprintf(2, '设计点:a1-a7=[%.4f,%.4f,%.4f,%.4f,%.4f,%.4f,%.4f]\n', x); end end % -------------------------- 其他辅助函数(保持稳定) -------------------------- function [f, c, ceq] = obj_fun(x, config) ceq = []; [f, c, ~, success] = eval_design(x, config); if ~success f = inf; c = [1e9; 1e9]; end % 记录日志 fid = fopen(config.OptLog, 'a'); fprintf(fid, '%d,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6e\n', ... optimoptions('fmincon').MaxIterations, f, x(1), x(2), x(3), x(4), x(5), x(6), x(7), ... res.uz1, res.uz2, res.uz3, res.maxStress); fclose(fid); end function generate_report(config, x_opt, initMass, initRes, optMass, optRes, exitflag, output) fid = fopen(config.ReportFile, 'w'); fprintf(fid, '天线桁架优化报告\n生成时间:%s\n', datestr(now)); fprintf(fid, '1. 设计变量优化:\n'); for i = 1:7 fprintf(fid, ' a%d:%.4f→%.4f(变化率:%.2f%%)\n', ... i, 1, x_opt(i), (x_opt(i)-1)/1*100); end fprintf(fid, '2. 性能对比:\n'); fprintf(fid, ' 质量:%.4f→%.4f(优化率:%.2f%%)\n', ... initMass, optMass, (initMass-optMass)/initMass*100); fprintf(fid, ' 最大应力:%.2f→%.2f MPa\n', initRes.maxStress/1e6, optRes.maxStress/1e6); fclose(fid); fprintf('✅ 报告生成:%s\n', config.ReportFile); end ❌ 设计点失败:Environment variable names must be nonmissing scalar strings or character row vectors. 设计点:a1-a7=[1.0000,1.0000,1.0000,1.0000,1.0000,1.0000,1.0000] 目前报出错误使用 run_optim 初始点计算失败!请先解决ANSYS调用问题(查看日志:C:\Users\lsj\matlabwj\ANSYS_Work\ANSYS_Run.log),帮我调整下matlab代码解决此问题
最新发布
11-29
%% 1. 参数设置 n_samples = 604; % 样本数量 n_features = 10; % 自变量个数 %% 2. 生成模拟数据(实际应用中替换为你的数据) rng(123); % 设置随机种子以便复现 % 生成10个自变量(例如:服从标准正态分布) X = SSSS; % 真实系数(模拟真实关系,可用于生成因变量) true_coeffs = (1:n_features)' / 5; % 假设系数随变量编号线性增长 intercept = -2; % 线性组合 linear_combination = intercept + X * true_coeffs; % 转换为概率(logistic 函数) prob = 1 ./ (1 + exp(-linear_combination)); % 生成二分类因变量(根据概率抽样) y = binornd(1, prob); % 将数据组合成表格(推荐方式) var_names = "X" + string(1:n_features); tbl = array2table(X, 'VariableNames', var_names); tbl.y = S3; % 添加因变量 disp('数据已生成:'); disp("样本数: " + n_samples); disp("特征数: " + n_features); %% 3. 拟合逻辑回归模型 % 使用广义线性模型('binomial' 分布 + logit 链接函数) formula = 'y ~ X1 + X2 + X3 + X4 + X5 + X6 + X7 + X8 + X9 + X10'; model = fitglm(tbl, formula, 'Distribution', 'binomial'); % 显示模型结果 disp(model); %% 4. 提取关键结果 % 回归系数、p值、置信区间 coeffs = model.Coefficients.Estimate; p_values = model.Coefficients.pValue; CI = model.Coefficients.SE; % 标准误,也可用 model.CoefficientCovariance % 输出每个变量的 odds ratio(优势比) odds_ratios = exp(coeffs); % 对数优势比取指数 fprintf('\n%10s\t%8s\t%8s\t%8s\t%12s\n', 'Variable', 'Estimate', 'SE', 'p-value', 'Odds Ratio'); for i = 1:height(model.Coefficients) var_name = model.CoefficientNames{i}; fprintf('%10s\t%8.4f\t%8.4f\t%8.4f\t%12.4f\n', ... var_name, coeffs(i), CI(i), p_values(i), odds_ratios(i)); end %% 5. 模型性能评估 % 预测概率 y_prob = model.Fitted.Probability; % 预测类别(阈值0.5) y_pred = double(y_prob >= 0.5); % 混淆矩阵 C = confusionmat(y, y_pred); fprintf('\n混淆矩阵:\n'); disp(C); % 准确率 accuracy = sum(y == y_pred) / length(y); fprintf('准确率: %.4f\n', accuracy); % % ROC 曲线与 AUC % [X_roc, Y_roac, T, AUC] = perfcurve(y, y_prob, 1); % figure; % plot(X_roc, Y_roc, 'LineWidth', 2); % xlabel('1-Specificity'); ylabel('Sensitivity'); % title(sprintf('ROC Curve (AUC = %.4f)', AUC)); % grid on;
09-08
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值