XIAN-FEM-2026June/3D opticsfem-master/compare/export_comsol_slice.m

46 lines
1.4 KiB
Matlab
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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