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.