Open In App

Write Data to Text Files in MATLAB

Improve
Improve
Like Article
Like
Save
Share
Report

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)

Here,

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: 

Matlab




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


Output:

 

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

Example 2:

Matlab




% 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';  
file=fopen('Gfg.txt','w');
fprintf(file,formatSpec,a);
fclose(file);


Output:

 

Example 3: 

Matlab




% 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);
fclose(fileID);


Output:

 

Example 4: 

Matlab




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


Output:

 



Last Updated : 04 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads