现在的位置: 首页 > 综合 > 正文

TeX系列: MATLAB和LaTeX结合绘图

2013年09月02日 ⁄ 综合 ⁄ 共 2464字 ⁄ 字号 评论关闭

目的是在MATLAB中绘图,在LaTeX中利用PGFPlots实现对图的修饰,比如坐标系、坐标轴标记、标题等等。这样能够保证图的中标记与正文文本的一致性,同时又可利用MATLAB强大的数据处理和丰富的绘图功能。整个过程比较顺畅,可以一试。

 

假设LaTeX文档所在的文件夹是E:\TeX,如下MATLAB代码构成的脚本文件保存在该文件夹下,改变MATLAB的当前目录为E:\TeX,执行该MATLAB脚本,在当前目录下得到如下pdf文档。

 

 MATLAB代码:

%% 第一个图
figname='fig1';
% 绘图
x=linspace(0,3*pi,20);
plot(x,sin(x)+100,'-o',x,100+x.^2/20)
% 绘图结束
axis off
set(gca,'Position',[0,0,1,1])
set(gcf,'PaperSize',[8,8])
set(gcf,'PaperPosition',[0.01,0.01,7.98,7.98])
lim=get(gca,'xlim');
set(gca,'xlim',[lim(1) lim(2)+(lim(2)-lim(1))/19])
lim=get(gca,'ylim');
set(gca,'ylim',[lim(1) lim(2)+(lim(2)-lim(1))/19])
print('-dpdf',figname);
dlmwrite([figname '.dat'],[get(gca,'xlim');get(gca,'ylim');get(gca,'zlim')],' ');
%% 第二个图
figname='fig2';
% 绘图
peaks(300);
shading interp
view([0,90])
% 绘图结束
axis off
set(gca,'Position',[0,0,1,1])
set(gcf,'PaperSize',[8,8])
set(gcf,'PaperPosition',[0.01,0.01,7.98,7.98])
set(gca,'XLimMode','manual')
print('-dpdf',figname);
dlmwrite([figname '.dat'],[get(gca,'xlim');get(gca,'ylim');get(gca,'zlim')],' ');

%% 编译LaTeX文档
!pdflatex exam.tex

LaTeX文档(exam.tex):

\documentclass[a4paper]{article}
\usepackage{CJK}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{width=8cm,compat=1.3}
\begin{document}
\begin{CJK*}{GBK}{kai}
\thispagestyle{empty}

\pgfplotstableread{fig1.dat}\loadedtable
\pgfplotstablegetelem{0}{[index]0}\of{\loadedtable}
\edef\xmin{\pgfplotsretval}
\pgfplotstablegetelem{0}{[index]1}\of{\loadedtable}
\edef\xmax{\pgfplotsretval}
\pgfplotstablegetelem{1}{[index]0}\of{\loadedtable}
\edef\ymin{\pgfplotsretval}
\pgfplotstablegetelem{1}{[index]1}\of{\loadedtable}
\edef\ymax{\pgfplotsretval}

\begin{center}
  这是第一个图
\end{center}

\begin{tikzpicture}
\begin{axis}[axis x line=bottom, axis y line=left,enlargelimits=false,axis on top]
  \addplot graphics [xmin=\xmin,xmax=\xmax, ymin=\ymin,ymax=\ymax] {fig1.pdf};
\end{axis}
\end{tikzpicture}

\pgfplotstableread{fig2.dat}\loadedtable
\pgfplotstablegetelem{0}{[index]0}\of{\loadedtable}
\edef\xmin{\pgfplotsretval}
\pgfplotstablegetelem{0}{[index]1}\of{\loadedtable}
\edef\xmax{\pgfplotsretval}
\pgfplotstablegetelem{1}{[index]0}\of{\loadedtable}
\edef\ymin{\pgfplotsretval}
\pgfplotstablegetelem{1}{[index]1}\of{\loadedtable}
\edef\ymax{\pgfplotsretval}


\begin{center}
  这是第二个图
\end{center}

\begin{tikzpicture}
\begin{axis}[enlargelimits=false,axis on top]
  \addplot graphics [xmin=\xmin,xmax=\xmax, ymin=\ymin,ymax=\ymax] {fig2.pdf};
\end{axis}
\end{tikzpicture}


\end{CJK*}
\end{document}

 

也许有一个更好的办法,使用matlab2tikz把matlab图形直接转化成tikzp/gfplots代码.  参见

http://blog.csdn.net/mathsoperator/article/details/6826208

抱歉!评论已关闭.