Writing and Reading Simple Text Data (MATLAB)

Working with text data is convenient as we can share our data with other systems without giving them the trouble to install a particular software to read our data.

Let’s see how we can read and write a text data using MATLAB.

Reading text data in MATLAB

Reading text Data

%% Reading the data in text file

fileID = fopen('nums.txt','r'); %opeing the file in reading mode

p=fscanf(fileID,'%s %s',2); %reads the header

formatSpec = '%d %f'; %defining the format of the data

sizeA = [2 Inf]; %defining the size of the data

A = fscanf(fileID,formatSpec,sizeA); %reading the data using fscanf function

fclose(fileID); %closing the file

A' %displaying the data

Writing Text Data

clear; close all; clc;

%% Defining the variables

x = 1:10;

y = [x;10*rand(1,10)]; %randomly generated 2nd column

z=['x-values' '  ' 'random-values']; %writing the header

%% Writing the data in text file

fileID = fopen('nums.txt','w'); %opens a text file in writing mode

fprintf(fileID,'%s %s %s\n',z);


fprintf(fileID,' %d         %4.4f\n',y); %write the data y in the file. 

%The first column is written in digit format and second column in floating point format.

fclose(fileID); %close the file

MATLAB Scripts:

Reading text data

Writing text data

—Utpal Kumar (IES,  Academia Sinica)

2 thoughts on “Writing and Reading Simple Text Data (MATLAB)”

  1. For people working with .sac data, they are easy functions to read and write the seismic signals with Matlab. (Where can I post them ?)


  2. @Alex: yes, there are many functions available on web that can be used to read sac data in MATLAB. We have just added one post which also deals with using sac data in MATLAB. Thanks for your comment!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s