Write Data to Text Files in MATLAB
Writing data to a text file means creating a file with data that will be saved on a computer’s secondary memory such as a hard disk, CD-ROM, network drive, etc. fprintf() function is used to write data to a text file in MATLAB. It writes formatted text to a file exactly as specified. The different escape sequences used with fprintf() function are:
\n : create a new line \t : horizontal tab space \v : Vertical tab space \r : carriage return \\ : single backslash \b : backspace %% : percent character
The format of the output is specified by formatting operators. The formatSpec is used to format ordinary text and special characters. A formatting operator starts with a percent sign% and ends with a conversion sign. The different format specifiers used with fprintf() function are:
%d or %i: Display the value as an integer %e : Display the value in exponential format %f : Display floating point number %g : Display the value with no trailing zeros %s : Display string array (Unicode characters) %c : Display single character(Unicode character)
Now let’s start writing data to a text file. Before writing to a file, we need to open the text file using fopen() function. To open a file, the syntax is:
fopen() function accepts two arguments:
- name of the file or File_identifier.
- type of access mode in which the file is to be open. We need to write data, so the access mode can be ‘w’, ‘w+’, ‘a’, ‘a+’.
Let’s see different ways to write data to text files are:
Note: If the file name is not specified then the result will be displayed on the screen.
Please Login to comment...