MATLAB For Beginners: 20-Minute Video Training Course. (Grab The Training Course and The Cheat Sheet for FREE)
The error I made in the past was writing documents by hand, which was more time consuming and error-prone. Additionally, the document was of a more modest quality and never up to date.
The solution was to automate the generation of the documentation.
1. Opening and Closing a Word File from MATLAB
If you want to write data into a Word file, you first need to open it. The function below has been created to open a word file and to output a structure that will be used to identify the file you want to write on:
function fid = fopenWord(wordFile) word = actxserver('Word.Application'); word.Visible = 1; if ~exist(wordFile, 'file'); % create new document: fid.handle = invoke(word.Documents, 'Add'); invoke(fid.handle, 'SaveAs', [pwd '/' wordFile]); else % open existing document: fid.handle = invoke(word.Documents, 'Open', [pwd '/' wordFile]); end fid.actx = word; return
This function will:
- Open a Word file with the name given by the variable wordFile if the file already exists in the current folder.
- Open a new Word file with the name given by the variable wordFile if the file does not already exist.
When you are done with writing into the file, you then need to close it:
function fcloseWord(fid) handle = fid.handle; word = fid.actx; % save the Word file invoke(handle, 'Save'); % close Word word.Quit(); return
Below is an example of using the 2 functions. In this example, we create a new Word file, save it and close it, and then open the file as if you clicked on it from your computer.
clc % name of your file wordFile = 'myWordFile.doc'; % open your Word file fid = fopenWord(wordFile); %−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− % write into your word file %−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− % close your word file fcloseWord(fid); % open the file as if you clicked on it winopen(wordFile);