我的一般任务是:创建一个Matlab函数,将矩阵结果转换为LaTeX格式,然后将其复制并粘贴到LaTeX源代码中。
我在Matlab中发现了latex()
函数,对我有很大帮助。但是小数位数有问题。我发现vpa()
函数可以通过设置精度来提供帮助。但是如果我这样做
digits(precision);
t = latex(sym(vpa(A)));
它没有按我的预期工作。例如
A = [0.00101; 0.01010; 0.10101;
1.10101; 1.01010; 1.00101;
11.10101; 11.01010; 11.00101]
digits(5);
latex(sym(vpa(A)))
我明白了
ans =
'\left(\begin{array}{c}
0.00101\\ 0.0101\\ 0.10101\\ 1.101\\ 1.0101\\ 1.001\\ 11.101\\ 11.01\\ 11.001
\end{array}\right)'
vpa()
函数(从doc返回“至少d个有效数字”,而不是小数。我知道。有什么办法可以安排我总是得到最大的。 5位小数?因此:
ans =
'\left(\begin{array}{c}
0.00101\\ 0.0101\\ 0.10101\\ 1.10101\\ 1.0101\\ 1.00101\\ 11.10101\\ 11.0101\\ 11.00101
\end{array}\right)'
答案 0 :(得分:0)
您可以仔细遍历列和行,并用sprintf
格式化条目。
% Matrix to be rendered with LaTeX
A = [rand(4,4) + eye(4); [1;1;0;0]];
% sprintf string format - here, a float with 3 decimal places
% padded with whitespace to be at least 6 characters long
strfmt = '%6.3f';
% Initialise string - could be initialised as e.g.
% s = sprintf('\\begin{pmatrix}\n');
s = '';
% Print entries of the first row of A, with columns separated by ampersands (&)
s = strcat(s, sprintf(strfmt, A(1,1)));
for c = 2:columns
s = strcat(s, sprintf([' & ', strfmt], A(1, c)));
end % for c
% Print rows of A, with lines separated by newline
% (\\ - escaped as \\\\, then \n is newline within the string, not required)
for r = 2:rows
s = strcat(s, sprintf([' \\\\\n', strfmt], A(r, 1)));
for c = 2:columns
s = strcat(s, sprintf([' & ', strfmt], A(r, c)));
end % for c
end % for r
% could finish with e.g.
% s = strcat(s, sprintf('\n\\end{pmatrix}\n');
这里的输出是
s =
10.815 & 0.632 & 0.958 & 0.957 & 1.000 \\
0.906 & 10.098 & 0.965 & 0.485 & 1.000 \\
0.127 & 0.278 & 10.158 & 0.800 & 0.000 \\
0.913 & 0.547 & 0.971 & 10.142 & 0.000
您可以用自己喜欢的乳胶矩阵环境(我喜欢pmatrix
,它需要amsmath
包)包围它。
在问题给出的问题中,A
是要呈现的矩阵,而strfmt
将是%.5f
。