Read and Write numbers with Matlab. Numerical Formats.

We will show how to read and write numbers using Matlab

Format numbers in Matlab

x=1/3 %by default format = format short
x = 0.3333
format long
x =
format short e
x =
format long e
x =
format rat %closest rational to the real value
x =
format %returns to the default value

Show values on the screen

There are two main ways of showing a number as output on the command window.
message=['present value = ', num2str(x)]; %as a string vector
present value = 0.33333
or using fprintf with formats:
fprintf('present value = %8.6f \n',x); % notice the format
present value = 0.333333
fprintf('present value = %6.4e \n',x); % notice the format
present value = 3.3333e-01

Write values on a file

filename='values.txt'; %assign a name to the file
fout=fopen(filename,'w'); %open the file to write values
fprintf(fout, 'present value = %6.4f, next = %6.4f \n',x, 1000*x);
fprintf(fout, '\n');
fprintf(fout, 'present value = %6.4e, next = %6.4e \n',x, 1000*x);
fprintf(fout, '\n');
fprintf(fout, 'present value = %22.16e, , next = %22.16e \n',x,1000*x);
fclose(fout); %close the file
type('values.txt') %show the file contens
present value = 0.3333, next = 333.3333 present value = 3.3333e-01, next = 3.3333e+02 present value = 3.3333333333333331e-01, , next = 3.3333333333333331e+02
% edit('values.txt') %shows the file into the Matlab editor window

Write a vector

v = 0:10;
filename='vector.txt'; %assign a name to the file
fout=fopen(filename,'w'); %open the file to write values
fprintf(fout, 'First as a column \n');
for i=1:length(v)
fprintf(fout, '%6.4f \n',v(i)); %as a column vector
fprintf(fout, 'Now as a row \n');
for i=1:length(v)
fprintf(fout, '%6.4f, ',v(i)); %as a row vector
fclose(fout); %close the file
First as a column 0.0000 1.0000 2.0000 3.0000 4.0000 5.0000 6.0000 7.0000 8.0000 9.0000 10.0000 Now as a row 0.0000, 1.0000, 2.0000, 3.0000, 4.0000, 5.0000, 6.0000, 7.0000, 8.0000, 9.0000, 10.0000,

Write a Matrix

% You can write the elements one by one using two for loops, like in the vector case
filename='matrix1.txt'; %assign a name to the file
fout=fopen(filename,'w'); %open the file to write values
for i=1:5
for j=1:5
fprintf(fout,'%22.16e ',M(i,j));
fclose(fout); %close the file
7.3701553742159476e-02 9.6119498011053861e-01 1.3143979882441759e-03 2.9978470250157452e-01 3.4862443765989404e-01 7.6955165766204858e-01 4.6642496209956175e-01 9.8126790715465673e-01 1.5907282252573729e-01 2.5007473335306751e-01 8.1767702669434328e-01 7.8699648800082900e-01 5.7019418230845254e-01 6.6525628587259478e-01 3.4500338529386221e-01 7.4042553528049992e-01 4.2256808367720589e-01 3.4647055440846941e-01 6.8420278327485129e-01 3.2863259286550173e-01 7.5824878717796196e-01 9.4372995842959428e-01 5.5750305310906734e-01 7.9240936234829118e-01 9.2748553289211655e-01
% or directly using
save('matrix2.txt','M','-ascii') %as you can see we loose some precission
7.3701554e-02 9.6119498e-01 1.3143980e-03 2.9978470e-01 3.4862444e-01 7.6955166e-01 4.6642496e-01 9.8126791e-01 1.5907282e-01 2.5007473e-01 8.1767703e-01 7.8699649e-01 5.7019418e-01 6.6525629e-01 3.4500339e-01 7.4042554e-01 4.2256808e-01 3.4647055e-01 6.8420278e-01 3.2863259e-01 7.5824879e-01 9.4372996e-01 5.5750305e-01 7.9240936e-01 9.2748553e-01

Reading ascii data values

ascii is the usual codification for characters when programing. Numbers are included in this codification.
Usually we assumed that correct data are written in a txt file. In our case we compared the results when we read the two previous matrix files created in the upper section using different methods.
max(max(M-newM1)) %perfect precission is achieved
ans = 0
max(max(M-newM2)) %the error is increasing because no all decimals are saved
ans = 4.4085e-09

Write and read in an EXCEL spreadsheet

% Write on a xlsx file:
matH5=hilb(5); %one 5x5 matrix
filename = 'testdata.xlsx';
xlswrite(filename,matH5) %by default data are written from the fisrt cell.
% we can add more information using the appropiate cell range.
% Read from an xlsx file
max(max(matH5-newH5)) %max error (notice that the precission is preserved)
ans = 0
read other ranges
HH=xlsread(filename,'D4:J7') %notice that empty cell are NaN
HH = 4×6
0.1429 0.1250 NaN NaN NaN NaN 0.1250 0.1111 NaN NaN NaN NaN NaN NaN 1.0000 0.5000 0.3333 0.2500 NaN NaN 0.5000 0.3333 0.2500 0.2000
you can make zero these NaN using the isnan function.
HH(isnan(HH)) = 0
HH = 4×6
0.1429 0.1250 0 0 0 0 0.1250 0.1111 0 0 0 0 0 0 1.0000 0.5000 0.3333 0.2500 0 0 0.5000 0.3333 0.2500 0.2000

Using headers in a spreadsheet

Consider finally the case where there is text information in your xlms file (example from Matlab documentation)
% write
values = {1, 2, 3 ; 4, 5, 'x' ; 7, 'y', 9}; %it is a cell variable because it contains numbers and strings
headers = {'First','Second','Third'};
xlswrite('withHeaders.xlsx',[headers; values]);
% read
filename = 'withHeaders.xlsx';
A = xlsread(filename) %headers are ignored and non numerical entries are considered NaN
A = 3×3
1 2 3 4 5 NaN 7 NaN 9
xlRange = 'B2:C3'; %reading a precise range. Notice that the first row are the headers.
B = xlsread(filename,xlRange)
B = 2×2
2 3 5 NaN
all information
[num,txt,raw] = xlsread(filename)
num = 3×3
1 2 3 4 5 NaN 7 NaN 9
txt = 4×3 cell array
'First' 'Second' 'Third'
'' '' ''
'' '' 'x'
'' 'y' ''
raw = 4×3 cell


Using the testdata.xlms file, compute the mean value of each column and write a new file testdataMean.xlms containing this new row after the present data (like if you do the mean of each column using EXCEL).

Working with Files and Folders with Matlab

As an example, let's generate several xlsx files and work with them reading their contens and make some computation.
numFiles= 5
numFiles = 5
mkdir Data; %the folder Data must be created before to write files
for i=1:numFiles
xlswrite(['./Data/dataname' num2str(i) '.xlsx'],M);
Now we read the folder looking for the data file names
folder = '.\Data\';
files = dir([folder,'*.xlsx']); %all the
ans = 5
files(1).name % to see the names
ans = 'dataname1.xlsx'
Finally, as an example, we read all the files and add the cells (3,3) of each spreadsheet
suma = 0;
for i=1:size(files,1)
filename=files(i).name; %name of each file
A = xlsread([folder filename]);
suma = suma + A(3,3);
suma = 195

Exercise 2:

Using the above data files compute the mean of the first column using all the files.

(C) Numerical Factory 2019