Saving both code and results to a word file or a pdf file

20 visualizaciones (últimos 30 días)
Left Terry
Left Terry el 15 de Dic. de 2024 a las 19:22
Respondida: Umar el 15 de Dic. de 2024 a las 23:55
Hi. Is there a way to save to a word or to a pdf file the code and its results at once ? The publish option gives an error because i use input() and, besides that, i don't like how it looks. I used the print option but it only saves the code (in a very nice looking way) but not the results.

Respuesta aceptada

Umar
Umar el 15 de Dic. de 2024 a las 23:55

Hi @Left Terry ,

To achieve the goal of saving both your MATLAB code and its results into a Word or PDF file, there are several approaches you can take:

Using diary Command: The diary command in MATLAB can log your commands and their outputs to a text file. Here’s how you can do this effectively:

Use the command diary filename.txt to start logging all commands and outputs.

   diary myDiaryFile.txt

Execute Your Code: Run your MATLAB code, including any calculations and outputs you want to capture.

   a = 1;
   b = sin(a);
   x = ones(4);
   disp(x);

Stop Logging: After running your code, use diary off to stop logging.

   diary off

Convert to Word/PDF: Open the text file in a text editor (like Notepad or TextEdit), copy the content, and paste it into a Word document. You can then save or export this document as a PDF.

Using fprintf for Custom Formatting: If you want more control over how your output appears in the final document, consider using fprintf to write both code and results into a text file directly:

fileID = fopen('output.txt', 'w');
fprintf(fileID, 'Code:\n');
fprintf(fileID, 'a = 1;\n');
fprintf(fileID, 'b = sin(a);\n');
fprintf(fileID, 'x = ones(4);\n\n');
fprintf(fileID, 'Results:\n');
a = 1;
b = sin(a);
x = ones(4);
fprintf(fileID, 'a: %d\n', a);
fprintf(fileID, 'b: %.2f\n', b);
fprintf(fileID, 'x:\n');
fprintf(fileID, '%d %d %d %d\n', x);  % Adjust based on dimensions
fclose(fileID);

After creating this output file, you can similarly copy it into Word or convert it to PDF.

If you're using MATLAB R2016a or later, consider using Live Scripts (*.mlx). Live Scripts allow you to combine code, output, and formatted text in one document: Start a new live script from the Home tab. Write Your Code. Enter your MATLAB code in sections. As you run each section, the output will appear directly below it. You can export your live script as a PDF by going to the Export option under the Live Editor tab.

Hope this helps.

Más respuestas (0)

Categorías

Más información sobre Live Scripts and Functions en Help Center y File Exchange.

Productos


Versión

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by