Open a .tex file, modify it in MATLAB, and then save it in a .tex file again (+ possibly compile it)

31 ビュー (過去 30 日間)
Nick
Nick 2015 年 10 月 3 日
コメント済み: Lisa 2023 年 8 月 4 日
Let's say I have a tex file, say MWE.tex, whose content is
\documentclass[11pt]{report}
\RequirePackage{amssymb, amsfonts, amsmath, latexsym, verbatim, xspace, setspace}
\RequirePackage{tikz, pgflibraryplotmarks}
\usepackage[margin=1in]{geometry}
\begin{document}
In this report we use x = VARX and y = VARY.
\end{document}
I would like to open in MATLAB, substitute VARX and VARY with values that come from some functions and save them in another .tex file. For instance VARX is the result of randi(10) and VARY is the result of randi(5).
What's the simplest solution to do this?
Would it also be possible to launch the latex compiler from Matlab? How?

回答 (2 件)

Nick
Nick 2015 年 10 月 4 日
I think I got it
text = fileread('MWE.tex');
newtext = strrep(text,'VARX',num2str(randi(10)));
newtext = strrep(newtext,'VARY',num2str(randi(5)));
fileID = fopen('newMWE.tex','w');
fprintf(fileID,'%s',newtext);
fclose(fileID);
command = 'pdflatex newMWE.tex';
[status,cmdout] = system(command)

Walter Roberson
Walter Roberson 2015 年 10 月 3 日
The simplest way is to open the file for reading, open a different file for writing, and copy lines from the input to the output until you reach the line you want to change, at which point you send the changed line to output instead of copying. After that resume copying until you reach the end of the input; then close both files.
Changing a text file "in place" can only work if the changed version has exactly the same size as what is being changed. Most of the time that isn't the case.
  1 件のコメント
Walter Roberson
Walter Roberson 2015 年 10 月 4 日
You can use system() to invoke the tex compiler. You can construct the string to system() by using sprintf() if you want to include the content of variables.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by