↓

在matlab中为绘图中的中英文字符串使用不同的字体

··

废话不多说,直接上代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function out = texWrap(inputStr, options)
% 包装字符串,为英文和中文(非英文)分别指定字体,可用于默认的tex解释器,以免出现口口口
% 默认的字体为宋体/Times New Roman
% 例如:
%   xlabel(texWrap("拉力/kN"))
%   xlabel(texWrap("拉力/kN", cnFontName = "黑体", enFontName = "Tahoma"))
% 实践时可以用函数包装目标函数或者wrap函数本身,例如:
%   xlbl = @(x) xlabel(texWrap(x));
%   或者
%   p = @(x) texWrap(x, cnFontName = "黑体", enFontName = "Tahoma")
%   xlabel(p("拉力/kN"))

arguments
    inputStr {mustBeNonzeroLengthText}
    options.cnFontName {mustBeTextScalar} = "宋体"
    options.enFontName {mustBeTextScalar} = "Times New Roman"
end
if ~isstring(inputStr)
    inputStr = string(inputStr);
end

cnFontName = options.cnFontName;
enFontName = options.enFontName;

    function out = texWrapInternal(str)
        % 使用正则表达式分割字符串
        letterRange = "\x00-\x7F\x370-\x3FF";
        pattern = "((\s*[^"+ letterRange +"]+)+)|(["+ letterRange +"]+)";
        tokens = regexp(str, pattern, "tokens");
        segments = string(tokens);

        delims = ["\fontname{" + cnFontName + "}", "\fontname{" + enFontName + "}"];

        if isempty(regexp(segments(1), "(["+ letterRange +"]+)", "tokens"))
            delims = fliplr(delims);
        end

        % 使用两次join拼接最终输出的字符串
        pairLen = floor(length(segments)/2);
        pairs = strings(pairLen, 1);

        for i = 1:pairLen
            start = 2*i - 1;
            pairs(i) = segments(start:start+1).join(delims(1));
        end

        if mod(length(segments), 2)
            pairs(end+1) = segments(end);
        end

        out = delims(2) + (pairs.join(delims(2)));
    end

out = arrayfun(@texWrapInternal, inputStr);
end