


The fprintf command is also used as a way to display data to the screen, and will utilize the same ‘%’ placeholders. This allows the file to be written to (not read only) through other programs such as Excel or Notepad++. At the end of this example, we also closed the file using the ‘fclose’ command. The extra trailing zeros are added since we specified that the floating point number have a width of 8, and the precision be 3. In this example two lines will be stored, with the first row displaying Inches 5.000 and the second line Centimeters 12.700. In these examples we have been storing integer values, but strings (%s), characters (%c), floating point values (%f), can all be stored in similar fashion.įprintf(fid,'%s\t%8.3f\n','Inches',A(1)) įprintf(fid,'%s\t%8.3f\n','Centimeters',A(2)) What happens if you have an unknown sized matrix? You do not want to manually type in several ‘%d\t’ into the fprintf command, and therefore one workaround is to use the ‘size’ and ‘repmat’ functions. The correct fprintf command will therefore be: To properly display the matrix, you will need to transpose matrix A. In order to do so, we might run the following:īut when you open the file ‘example.txt’, oh no! You’ll see that the matrix has been written as ! During the write process, fprintf will read down each column instead of across each row.

They will be tab delimited (\t), and after every three integers written, we will begin again on a new line (\n). To save this data to ‘example.txt’, we will store three integers (%d) across each row. Now let’s try to save some data.Īssume, we have the 2 x 3 array A = There are several other options such as ‘a’ which appends to a file. (Note: if fid equals -1, there was an error in opening the file). The ‘w’ argument allows us to create and write to the file. In this case, the file will be located in the current working directory, under the name ‘example.txt’. This can be done using the fopen command: Prior to saving data, you need to initialize a file id. Let’s run through some examples to get you familiar with the concepts. The Matlab fprintf function uses single quotes to de ne the format string. One easy way to do so is via the fprintf command. In this MATLAB project, the maximum likelihood estimator is analysed in the. Specify the Precision of the Floating Point Fields fprintf(’ Equal precision control for all float types ’) for j1:length(x) fprintf(’d.
MATLAB FPRINTF CODE
Saving data to a text file can be a useful way to access results of your Matlab code at a later time. fprintf ME 352, Fall 2008 page 3/6 The following sequence of modi cations to the format string provide increasing levels of control over the column appearance.
