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
x =
3.333333333333333e-01
format rat %closest rational to the real value
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
or using fprintf with formats:
- %f (floating point)
- %e (with exponent)
- %d (integers)
- %s (string characters)
fprintf('present value = %8.6f \n',x); % notice the format
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, 'present value = %6.4e, next = %6.4e \n',x, 1000*x);
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
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');
fprintf(fout, '%6.4f \n',v(i)); %as a column vector
fprintf(fout, 'Now as a row \n');
fprintf(fout, '%6.4f, ',v(i)); %as a row vector
fclose(fout); %close the file
type('vector.txt')
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
fprintf(fout,'%22.16e ',M(i,j));
fclose(fout); %close the file
type('matrix1.txt')
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
save('matrix2.txt','M','-ascii') %as you can see we loose some precission
type('matrix2.txt')
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.
newM1=load('matrix1.txt','-ascii');
max(max(M-newM1)) %perfect precission is achieved
newM2=load('matrix2.txt','-ascii');
max(max(M-newM2)) %the error is increasing because no all decimals are saved
Write and read in an EXCEL spreadsheet
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.
xlswrite(filename,matH4,'F6:I9');
newH5=xlsread(filename,'A1:E5');
max(max(matH5-newH5)) %max error (notice that the precission is preserved)
read other ranges
HH=xlsread(filename,'D4:J7') %notice that empty cell are NaN
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
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)
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]);
filename = 'withHeaders.xlsx';
A = xlsread(filename) %headers are ignored and non numerical entries are considered NaN
xlRange = 'B2:C3'; %reading a precise range. Notice that the first row are the headers.
B = xlsread(filename,xlRange)
all information
[num,txt,raw] = xlsread(filename)
'First' 'Second' 'Third'
'' '' ''
'' '' 'x'
'' 'y' ''
raw = 4×3 cell
| 1 | 2 | 3 |
---|
1 | 'First' | 'Second' | 'Third' |
---|
2 | 1 | 2 | 3 |
---|
3 | 4 | 5 | 'x' |
---|
4 | 7 | 'y' | 9 |
---|
Excercise1:
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.
mkdir Data; %the folder Data must be created before to write files
xlswrite(['./Data/dataname' num2str(i) '.xlsx'],M);
Now we read the folder looking for the data file names
files = dir([folder,'*.xlsx']); %all the
files(1).name % to see the names
Finally, as an example, we read all the files and add the cells (3,3) of each spreadsheet
filename=files(i).name; %name of each file
A = xlsread([folder filename]);
Exercise 2:
Using the above data files compute the mean of the first column using all the files.
(C) Numerical Factory 2019