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,'\n');

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)