解决问题,数值矩阵转换成latex直接输入Word中的MathType或者latex文本编辑器,matlab没有数值矩阵转latex,如果丝符号矩阵可以使用latex直接输出,但计算中有些结果时使用double将符号矩阵转换成数值作为输出,此时写报告要数值的,没法直接复制,故网上 寻找可用代码,下面代码摘抄于https://frenselx.wordpress.com/2006/08/07/%e6%8a%8amatlab%e7%9a%84%e6%95%b0%e5%80%bc%e7%9f%a9%e9%98%b5%e8%be%93%e5%87%ba%e6%88%90latex%e8%af%ad%e5%8f%a5/,如有侵权,请联系删除, 感谢“”“大肥維的年記”。
把Matlab的数值矩阵输出成Latex语句
近来在写一份note,要经常写上Matlab算出来的矩阵,由本我是用Latex来编写,所以需要把Matlab的数值矩阵转成Latex语句。Matlab中看来没有把数值矩阵转成Latex语句的程序,而只有关于符号矩阵的程序(其实是Maple的),所以我就自己写了一个。我的程序可能写得很烂,但还能凑合用一用。
% 数值矩阵输出成Latex代码
% A为矩阵,precision为输出精度
% 如输入:
% >> a = [1 2 3; 4 5 6; 7 8 9];
% >> latex2(a)
% \left(
% \begin{array}{ccc}
% 1 & 2 & 3 \\
% 4 & 5 & 6 \\
% 7 & 8 & 9 \\
% \end{array}
% \right)
function f = latex2(A, precision)
% 没输入精度参数时,默认精度为小数后4位
if nargin == 1
precision = ‘4’;
else
precision = int2str(precision);
end
% 定义单一元素输出格式
out_num = [‘ %0.’ precision ‘f &’];
% 用作整数输出判断
z = zeros(1, str2num(precision) + 1);
z(1) = ‘.’;
z(2 : end) = ‘0’;
z = char(z);
% 求矩阵大小
[r c] = size(A);
nc = zeros(1, c);
nc(:) = 99; % 存放character c
% 生成第一句Latex语句
out = sprintf(‘\\left(\n\t\\begin{array}{%s}’, char(nc));
% 二重循环,用作生成整个矩阵的Latex语句
for i = 1 : r
out = [out sprintf(‘\n\t’)]; % 换行
for j = 1 : c
temp = sprintf(out_num, A(i, j));
% 小数位皆为零时,把数取整。如1.0001取为1
dot_position = find(temp == ‘.’);
if temp(dot_position : end – 2) == z
temp = temp(1 : dot_position – 1);
temp = [temp ‘ &’];
% 要取整时,如有负号,则必须丢掉
if temp(2) == ‘-‘
temp = [temp(1) temp(3 : end)];
end
end
out = [out temp];
end
% 丢掉最后的’&’号
out = out(1 : end – 1);
% 行末加上’\\’号
out = [out ‘\\’];
end
% 加上最后一句结束代码
out = [out sprintf(‘\n\t\\end{array}\n\\right)’)];
f = out;