Skip to content
Related Articles
Open in App
Not now

Related Articles

Write Data to Text Files in MATLAB

Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • Last Updated : 04 Jul, 2022
Improve Article
Save Article
Like Article

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:

f=fopen(File_name, Access_mode)


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:

Example 1: 


% Writing array of integers
a= [1,2,3,4; 5,6,7,8; 9,10,11,12;13,14,15,16];
fprintf(file, '%3d %3d %3d %3d \n',a);



Note: If the file name is not specified then the result will be displayed on the screen.

Example 2:


% Writing floating point values and 
% string literals to a text file
a = [1.500,2.500, 3.500,4.500];
% 4.2 means floating number with 4 digits
% including 2 digits after the decimal point
formatSpec = 'a is %4.2f \n';  



Example 3: 


% MATLAB code for Writing data to
% text file using mathematical function
x = 1:10;
A = x.^2;
fileID = fopen('power.txt','w');
fprintf(fileID,'%4s %4s\n','x','power^2');
fprintf(fileID,'%4.2f %5.2f\n',A);



Example 4: 


% MATLAB code for writing 
% hyperlink to a text file
sitename = 'Web Site for geeks';
fprintf(f,'<a href = "%s">%s</a>\n',url,sitename);



My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!