function export_comsol_slice(mphFile, outFile, z0, nx, ny) %EXPORT_COMSOL_SLICE Export |E| on z=z0 plane from COMSOL mph (LiveLink required). % % 不要无参调用本函数。请直接运行: run_export_comsol.m % % 或手动带齐 3 个参数: % export_comsol_slice('D:\path\SBC.mph', 'data\comsol_z050.txt', 0.5); if nargin < 3 error(['输入参数不足。\n' ... '请运行 run_export_comsol.m(推荐),或:\n' ... ' export_comsol_slice(''完整路径\\SBC.mph'', ''data\\comsol_z050.txt'', 0.5);']); end if nargin < 4, nx = 121; end if nargin < 5, ny = 121; end assert(isfile(mphFile), 'COMSOL model not found: %s', mphFile); assert(exist('mphload', 'file') == 2, ... 'COMSOL LiveLink for MATLAB not found (mphload missing).'); model = mphload(mphFile); x = linspace(-0.5, 0.5, nx); y = linspace(-0.5, 0.5, ny); [X, Y] = meshgrid(x, y); Z = z0 * ones(size(X)); coords = [X(:)'; Y(:)'; Z(:)']; expr = 'sqrt(realdot(ewfd.Ex,ewfd.Ex)+realdot(ewfd.Ey,ewfd.Ey)+realdot(ewfd.Ez,ewfd.Ez))'; val = mphinterp(model, expr, 'coord', coords, 'unit', 'V/m'); val = reshape(val, size(X)); outDir = fileparts(outFile); if ~isempty(outDir) && ~isfolder(outDir) mkdir(outDir); end fid = fopen(outFile, 'w'); fprintf(fid, '%% x(m) y(m) z(m) normE(V/m)\n'); for i = 1:numel(X) fprintf(fid, '%.6e\t%.6e\t%.6e\t%.6e\n', X(i), Y(i), Z(i), val(i)); end fclose(fid); fprintf('Exported COMSOL slice to %s\n', outFile); end