How to Read Dat File in Matlab Script
So far, we accept indirectly discussed several methods of getting input data from the user, and several methods of outputting the result in a MATLAB program. This note attempts at formalizing all the previous discussions and innovate more general efficient methods of code interaction with users.
Methods of data input/output in MATLAB
Permit's begin with an example code that explains the meaning of input/output (I/O) in MATLAB,
a = 0.1 ; b = ane ; x = 0.6 ; y = a * exp ( b * x ) In the above lawmaking, a, b, x are examples of input information to code, and y is an example of code output. In such cases as in the to a higher place, the input data is said to be hardcoded in the program.
Input data can be fed to a MATLAB program in four different means,
- allow the user reply questions in a dialog in MATLAB terminal window,
- permit the user provide input on the operating system command line,
- allow the user write input information in a graphical interface,
- let the user provide input information in a file.
There are two major methods of data output,
- writing to the final window, equally previously done using
disp()function, or, - writing to an output file.
Nosotros accept already extensively discussed press output to the terminal window. Reading from and writing data to file is also easy as we will see here.
Input/output from MATLAB concluding window
We have already introduced and used this method frequently in the past, via the MATLAB'south built-in function input(). If we were to get the input data for the higher up lawmaking via the concluding window, an example approach would be the following,
datain = input ( 'input [a,b,c]: ' ); a = datain ( ane ); b = datain ( ii ); 10 = datain ( iii ); y = a * exp ( b * x ) input a,b,c: [0.1, 1, 0.6] y = 0.1822 One could too read the input values every bit string ans then catechumen them to real values or parse the input using one of MATLAB's built-in functions, for example,
>> datain = input ( 'input [a,b,c]: ' , 'southward' ); input [ a , b , c ]: [ 0.1 , 1 , 0.6 ] >> form ( datain ) >> datain = str2num ( datain ) datain = 0.1000 one.0000 0.6000 >> a = datain ( one ); >> b = datain ( 2 ); >> ten = datain ( 3 ); >> y = a * exp ( b * x ) Input/output data from operating system'southward command line
This approach is most popular in Unix-like environments, where most users are accustomed to using the Fustigate command line. Nonetheless, it tin can be readily used in Windows cmd environment as well. For this approach, nosotros have to invoke MATLAB from the computer operating arrangement'due south command line, that is, Fustigate in Linux systems, and cmd in Windows,
start matlab -nosplash -nodesktop -r "testIO" And so a MATLAB control-line window opens in your reckoner similar the following that runs automatically your lawmaking (stored in testIO.yard).
In the to a higher place control, we are starting MATLAB from the OS control line with our own choice of optional arguments for MATLAB. You can specify startup options (too chosen control flags or command-line switches) that instruct the MATLAB programme to perform certain operations when y'all start it. On all platforms, specify the options as arguments to the MATLAB command when yous beginning at the operating organisation prompt. For instance, the following starts MATLAB and suppresses the display of the splash screen (a splash screen is a graphical control element consisting of a window containing an image, a logo, and the electric current version of the software. A splash screen commonly appears while a game or program is launching),
The flag -nodesktop result in opening simply the MATLAB command line, and no MATLAB Graphical user interface (GUI) just like the figure in a higher place. Finally, the flag -r executes the MATLAB file that appears right after it, specified as a cord or as the name of a MATLAB script or function. If a MATLAB statement is MATLAB code, you should enclose the string with double quotation marks. If a MATLAB statement is the name of a MATLAB function or script, do non specify the file extension and practise not use quotation marks. Whatsoever required file must be on the MATLAB search path or in the startup folder. You lot can also fix MATLAB's working folder right from the command-line using -sd flag. You lot can find find more information about all possible flags here. On Windows platforms, you lot can precede a startup selection with either a hyphen (-) or a slash (/). For example, -nosplash and /nosplash are equivalent.
Annotation that you lot can besides quote MATLAB on the OS control line, along with the name of the script you want to run. For example, suppose yous wanted to run the original script,
a = 0.1 ; b = ane ; x = 0.6 ; y = a * exp ( b * x ) Notwithstanding, now with a, b, x, given at runtime. You could write a script file test.m that contains,
and give the variables values at runtime, on Os command line, like the following,
matlab -nosplash -nodesktop -r "a = 0.1; b = 1; 10 = 0.6; testIO" The figure below shows a screen-shot illustrating the output of the in a higher place command.
Input/output data from a Graphical User Interface
This method of inputting data is done by constructing a Graphical User Interface (GUI) which opens and takes input from the user. This is probably one of the most convenient methods for users to input data. You can practise this in MATLAB for instance past using the born role inputdlg() which creates a dialog box that gathers user input. But this method of data collection is beyond the telescopic of our class. More than information about this can be found here.
Input/output data from file
In cases where the input/output information is large, the control-line arguments and input from the terminal window are not efficient anymore. In such cases, the most common approach is to let the code read/write data from a pre-existing file, the path to which is nigh often given to the code via the OS control line or MATLAB terminal window.
There are many methods of importing and exporting information to and from MATLAB, merely some of which we will discuss hither. For more data come across here, here, and here. The following table shows some of the most important import functions in MATLAB, which we will hash out here as well.
| Function | Description |
|---|---|
load() | Load MATLAB variables from file into MATLAB workspace |
salvage() | relieve MATLAB variables from MATLAB workspace into a MATLAB `.mat` file. |
fscanf() | Read data from text file |
fprintf() | Write data to a text file |
dlmread() | Read ASCII-delimited file of numeric data into matrix |
dlmwrite() | Write a numeric matrix into ASCII-delimited file |
csvread() | Read comma-separated value (CSV) file |
csvwrite() | Write values of a matrix into a comma-separated (CSV) file |
xlswrite() | Read Microsoft Excel spreadsheet file |
xlswrite() | write data into a Microsoft Excel spreadsheet file |
readtable() | Create table from file |
writetable() | Write table to file |
imread() | Read paradigm from graphics file |
imwrite() | Write image to graphics file |
importdata() | Load data from file |
textscan() | Read formatted data from text file or cord |
fgetl() | Read line from file, removing newline characters |
fread() | Read data from binary file |
fwrite() | Write data to binary file |
blazon() | Display contents of file |
Loading/saving MATLAB workspace variables
MATLAB has two useful functions that can save the workspace variables into special MATLAB .mat files, to be later load again into the same or some other MATLAB workspace for further work or manipulation. The part save() saves workspace variables to a given file. The well-nigh useful options for this office are the following,
salvage ( filename ) salvage ( filename , variables ) save ( filename , variables , fmt ) -
relieve(filename)saves all variables from the current workspace in a MATLAB formatted binary file called MAT-file with the given proper nounfilename. If the filefilenameexists,save()overwrites the file. -
save(filename,variables)saves simply the variables or fields of a structure array specified pastvariables. For case,p = rand ( one , x ); q = ones ( 10 ); salve ( 'pqfile.mat' , 'p' , 'q' )volition create the binary MAT file pqfile.mat which contains the two variables.
-
salvage(filename,variables,fmt)saves the requested variables with the file format specified pastfmt. The variables statement is optional. If you do not specify variables, the save function saves all variables in the workspace. File format, specified as one of the post-obit. When using the command form of save, you do non demand to enclose the input in unmarried or double quotes, for instance,save myFile.txt -ascii -tabs. For example,p = rand ( 1 , ten ); q = ones ( ten ); save ( 'pqfile.txt' , 'p' , 'q' , '-ascii' )will create an ASCII text file pqfile.txt which contains the ii variables
pandq.
| Value of fmt | File Format |
|---|---|
'-mat' | Binary MAT-file format. |
'-ascii' | Text format with 8 digits of precision. |
'-ascii','-tabs' | Tab-delimited text format with 8 digits of precision. |
'-ascii','-double' | Text format with 16 digits of precision. |
'-ascii','-double','-tabs' | Tab-delimited text format with 16 digits of precision. |
Similarly, 1 can reload the same files into MATLAB workspace again if needed, for example using MATLAB load() office,
>> load ( 'pqfile.txt' ) >> pqfile pqfile = Columns one through 8 0.0975 0.2785 0.5469 0.9575 0.9649 0.1576 0.9706 0.9572 i.0000 one.0000 i.0000 ane.0000 1.0000 i.0000 1.0000 1.0000 1.0000 1.0000 ane.0000 one.0000 ane.0000 ane.0000 1.0000 1.0000 ane.0000 ane.0000 1.0000 1.0000 1.0000 1.0000 i.0000 i.0000 ane.0000 1.0000 1.0000 i.0000 1.0000 i.0000 1.0000 1.0000 i.0000 1.0000 one.0000 1.0000 1.0000 i.0000 i.0000 one.0000 1.0000 1.0000 i.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 ane.0000 1.0000 i.0000 1.0000 i.0000 1.0000 1.0000 1.0000 1.0000 i.0000 1.0000 1.0000 1.0000 1.0000 i.0000 i.0000 1.0000 1.0000 i.0000 i.0000 1.0000 1.0000 ane.0000 1.0000 1.0000 1.0000 1.0000 i.0000 1.0000 1.0000 Columns ix through ten 0.4854 0.8003 one.0000 ane.0000 1.0000 i.0000 1.0000 i.0000 1.0000 1.0000 ane.0000 1.0000 one.0000 1.0000 1.0000 1.0000 1.0000 i.0000 1.0000 1.0000 ane.0000 i.0000 But notation that upon loading the Ascii file, the information about the private variables is lost. By dissimilarity, loading data using the MAT file will preserve the structure of the variables,
>> load ( 'pqfile.mat' ) >> p p = Columns 1 through 8 0.1419 0.4218 0.9157 0.7922 0.9595 0.6557 0.0357 0.8491 Columns 9 through ten 0.9340 0.6787 q = 1 1 1 1 1 ane 1 1 1 ane 1 1 1 1 1 one 1 1 i 1 ane 1 one 1 1 1 1 1 ane one 1 1 1 1 1 1 one 1 1 1 1 one 1 1 1 1 1 1 1 1 ane 1 one ane 1 1 1 i ane 1 1 1 1 ane 1 1 1 ane 1 1 i 1 1 i 1 ane i 1 1 one 1 1 1 1 1 1 1 1 1 1 1 1 i 1 ane 1 ane 1 1 ane Reading/writing a formatted file using fscanf() and fprintf()
At that place are numerous methods of reading the contents of a file in MATLAB. The most trivial and probably least pleasing method is through MATLAB'south built-in function fscanf(). To read a file, say this file, you volition accept to outset open it in MATLAB,
fileID = fopen ( 'information.in' , 'r' ); formatSpec = '%f' ; A = fscanf ( fileID , formatSpec ) fclose ( fileID ); Note that unlike the C language'due south fscanf(), in MATLAB fscanf() is vectorized pregnant that information technology can read multiple lines all at in one case. Hither, the attribute 'r' states that the file is opened to read it (vs writing, or some other purpose). A listing of available options for fopen() is the post-obit,
| Attribute | Description |
|---|---|
'r' | Open file for reading. |
'w' | Open or create new file for writing. Discard existing contents, if any. |
'a' | Open or create new file for writing. Append information to the finish of the file. |
'r+' | Open file for reading and writing. |
'w+' | Open or create new file for reading and writing. Discard existing contents, if any. |
'a+' | Open up or create new file for reading and writing. Append information to the stop of the file. |
'A' | Open up file for appending without automatic flushing of the current output buffer. |
'Westward' | Open file for writing without automated flushing of the current output buffer. |
The general syntax for reading an assortment from an input file using fscanf() is the following,
array = fscanf ( fid , format ) [ array , count ] = fscanf ( fid , format , size ) where the optional statement size specifies the amount of information to exist read from the file. There are iii versions of this argument,
-
n: Reads exactlynorthwardvalues. Subsequently this statement,assortmentvolition be a column vector containingnvalues read from the file. -
Inf: Reads until the cease of the file. After this statement,assortmentwill be a cavalcade vector containing all of the information until the terminate of the file. -
[north thou]: Reads exactly, $n\times m$ values, and format the information as an $n\times chiliad$ array. For example, consider this file, which contains 2 columns of numeric data. I could read this information usingfscanf()like the following,>> formatSpec = '%d %f' ; >> sizeA = [ ii Inf ]; >> fileID = fopen ( 'nums2.txt' , 'r' ); >> A = transpose ( fscanf ( fileID , formatSpec , sizeA )) >> fclose ( fileID );A = 1.0000 2.0000 three.0000 4.0000 5.0000 0.8147 0.9058 0.1270 0.9134 0.6324
Now suppose you perform some on operation on A, say the elemental multiplication of A by itself. Then you want to store (append) the result into another file. You lot can exercise this using MATLAB office fprintf(),
>> formatSpec = '%d %f \n' ; >> fileID = fopen ( 'nums3.txt' , 'w+' ); >> fprintf ( fileID , formatSpec , A .* A ); >> fclose ( fileID ); The option w+ tells MATLAB to shop the result in a file named num3.txt, and if the file does already exist, then append the result to the end of the current existing file. To run into what formatting specifiers y'all can utilise with MATLAB fscanf() and fprintf(), see this folio.
MATLAB also has some rules to skip characters that are unwanted in the text file. These rules are really details that are specific to your needs and the all-time approach is to seek the solution to your specific problem by searching MATLAB'southward manual or the web. For example, consider this file which contains a prepare of temperature values in degrees (including the Celsius degrees symbol). 1 way to read this file and skipping the degrees symbol in MATLAB could be then the post-obit set up of commands,
>> fileID = fopen ( 'temperature.dat' , 'r' ); >> degrees = char ( 176 ); >> [ A , count ] = fscanf ( fileID , [ '%d' degrees 'C' ]) >> fclose ( fileID ); A = 78 72 64 66 49 count = five This method of reading a file is very powerful but rather detailed, low-level and cumbersome, peculiarly that you have to define the format for the content of the file appropriately. Most often, other higher-level MATLAB'southward built-in function come to rescue usa from the hassles of using fscanf(). For more data most this function though, if you lot really want to stick to it, see here. Some important MATLAB special characters (escape characters) that tin can also appear in fprintf() are also given in the post-obit tabular array.
| Symbol | Event on Text |
|---|---|
'' | Unmarried quotation mark |
%% | Single percent sign |
\\ | Unmarried backslash |
\north | New line |
\t | Horizontal tab |
\five | Vertical tab |
Reading/writing information using dlmread()/dlmwrite() and csvread()/csvwrite()
The methods discussed above are rather primitive, in that they require a bit of attempt by the user to know something most the structure of the file and its format. MATLAB has a long list of advanced IO functions that tin handle a broad variety of data file formats. Two of the almost common functions are dedicated specifically to read information files containing delimited data sets: csvread() and dlmread().
In the field of scientific computing, a Comma-Separated Values (CSV) data file is a blazon of file with extension .csv, which stores tabular information (numbers and text) in plain text format. Each line of the file is chosen a data tape and each record consists of 1 or more fields, separated past commas. The use of the comma as a field separator is the source of the proper noun for this file format.
Now suppose you wanted to read ii matrices whose elements were stored in CSV format in two csv data files matrix1.csv and matrix2.csv. Y'all can achieve this task simply by calling MATLAB's born csv-reader function called csvread(filename). Here the word filename is the path to the file in your local hard drive. For instance, download these two given csv files above in your MATLAB working directory and then effort,
>> Mat1 = csvread ( 'matrix1.csv' ); >> Mat2 = csvread ( 'matrix2.csv' ); Then suppose you desire to multiply these two vectors and store the result in a new variable and write it to a new output CSV file. You could practice,
Mat3 = Mat1 * Mat2 ; >> csvwrite ( 'matrix3.csv' , Mat3 ) which would output this file: matrix3.csv for yous.
Alternatively, you could also use MATLAB's built-in functions dlmread() and dlmwrite() functions to do the same things equally above. These two functions read and write ASCII-delimited file of numeric data. For instance,
>> Mat1 = dlmread ( 'matrix1.csv' ); >> Mat2 = dlmread ( 'matrix2.csv' ); >> Mat3 = Mat1 * Mat2 ; >> dlmwrite ( 'matrix3.dat' , Mat3 ); Notation that, dlmread() and dlmwrite() come with an optional argument delimiter of the post-obit format,
>> dlmread ( filename , delimiter ) >> dlmwrite ( filename , matrixObject , delimiter ) where the argument delimiter is the field delimiter character, specified equally a character vector or string. For example, in the in a higher place instance, the delimiter is comma ','. In other cases, y'all could, for instance, use white space ' ', or '\t' to specify a tab delimiter, and and then on. For example, you could take equally written,
>> dlmwrite ( 'matrix4.dat' , Mat3 , '\t' ); to create a tab-delimited file named matrix4.dat.
Reading/writing data using xlsread() and xlswrite()
Once data becomes more complex than simple numeric matrices or vectors, then we demand more complex MATLAB functions for IO. An example of such a example is when you have stored your data in a Microsoft Excel file. For such cases, yous tin can use xlsread(filename) to read the file specified by the input argument filename to this function. We will, afterwards on, see some example usages of this function in homework. Similarly, you could write information into an excel file using xlswrite(). For case,
>> values = { i , ii , three ; four , 5 , 'ten' ; 7 , viii , 9 }; >> headers = { 'First' , '2nd' , '3rd' }; >> xlswrite ( 'XlsExample.xlsx' ,[ headers ; values ]); would create this Microsoft Excel file for you.
Reading/writing information using readtable() and writetable()
Another important and highly useful set up of MATLAB functions for IO are readtable() and writetable(). The function readtable() is used to read data into MATLAB in the course of a MATLAB table data type. For instance, yous could read the aforementioned Excel file that we created above into MATLAB using readtable() instead of xlsread(),
>> XlsTable = readtable ( 'XlsExample.xlsx' ) XlsTable = Starting time Second 3rd _____ ______ _____ ane two '3' 4 5 'x' 7 8 '9' Reading and writing image files using imread() and imwrite()
MATLAB has a really broad range of input/output methods of data. We have already discussed some of the most useful IO approaches in the previous sections. For graphics files, however, none of the previous functions are useful. Suppose y'all wanted to import a jpg or png or some other type graphics file into MATLAB to further procedure it. For this purpose, MATLAB has the born function imread() which tin can read image from an input graphics file. For example, to read this image file in MATLAB, you lot could practice,
>> homer = imread ( 'homer.jpg' ); >> imshow ( homer ) to get the post-obit effigy in MATLAB,
At present suppose you want to convert this figure to blackness-and-white and save it as a new figure. You lot could do,
>> homerBW = rgb2gray ( homer ); >> imshow ( homerBW ) >> imwrite ( homerBW , 'homerBW.png' ); to get this black and white version of the to a higher place image, at present in png format (or in any format you may wish, that is also supported by MATLAB).
Reading a file using importdata()
Probably, the most general MATLAB office for data input is importdata(). This function can exist used to import almost any type of data and MATLAB is capable of automatically recognizing the correct format for reading the file, based on its extension and content. For example, you could read the same paradigm file above, using importdata(),
>> newHomer = importdata ( 'homer.jpg' ); >> imshow ( newHomer ) to import it to MATLAB. At the same time, you could also use it to import information from the excel file that we created above, XlsExample.xlsx,
>> newXls = importdata ( 'XlsExample.xlsx' ) newXls = data: [3x3 double] textdata: {3x3 jail cell} colheaders: {'First' '2nd' 'Third'} or similarly, read a csv-delimited file like matrix3.csv,
>> newMat3 = importdata ( 'matrix3.csv' ) newMat3 = Columns 1 through 7 62774 103230 77362 87168 65546 64837 100700 104090 143080 104700 116500 108250 105400 111110 80351 112850 89506 113890 106030 70235 110620 99522 134130 73169 134190 117710 92878 94532 59531 102750 91679 111350 80539 84693 96078 58504 76982 52076 91449 80797 69246 61569 76170 104310 93950 114860 89779 101530 87014 91610 118380 90636 107840 91120 90247 84871 85943 110670 73451 114410 100840 111660 77908 82570 94427 57213 81175 79305 78718 68662 Columns 8 through x 79446 78102 106570 102950 116850 137810 113210 108800 128700 93013 119130 132700 95750 100980 100450 67044 80635 78006 86355 103760 119710 92649 98589 132660 73117 109270 99401 65283 66888 114030 In general, you tin can employ importdata() to read MATLAB binary files (MAT-files), ASCII files and Spreadsheets, likewise as images and audio files.
Reading a file using fgetl()
Another useful MATLAB office for reading the content of a file is fgetl() which can read a file line by line, removing the new line characters \n from the stop of each line. The entire line is read as a string. For example, consider this file. One could read the content of this text file using the function fgetl() similar the following,
>> fid = fopen ( 'text.txt' ); >> line = fgetl ( fid ) % read line excluding newline character line = The primary benefit of using a weakly-typed linguistic communication is the ability to do rapid prototyping. The number of lines of code required to declare and use a dynamically allocated array in C (and properly clean up after its use) is much greater than the number of lines required for the aforementioned process in MATLAB. >> line = fgetl ( fid ) % read line excluding newline graphic symbol >> line = fgetl ( fid ) % read line excluding newline character line = Weak typing is likewise good for lawmaking-reuse. Yous can lawmaking a scalar algorithm in MATLAB and with relatively piffling try modify information technology to work on arrays as well every bit scalars. The fact that MATLAB is a scripted instead of a compiled linguistic communication also contributes to rapid prototyping. Reading data from spider web using webread()
In today'southward globe, it often happens that the information you need for your research is already stored somewhere on the world-wide-spider web. For such cases, MATLAB has built-in methods and functions to read and import information or even a webpage. For example, consider this page on this course's website. Information technology is indeed a text file containing a set of IDs for some astrophysical events. Suppose, yous needed to read and store these IDs locally on your device. You lot could simply attempt the following code in MATLAB to fetch all of the tabular array's data in a single string via,
>> webContent = webread ( 'https://www.cdslab.org/matlab/notes/data-transfer/io/triggers.txt' ) webContent = '00745966 00745090 00745022 00744791 00741528 00741220 00739517 00737438 ... 00100319' At present if we wanted to get the individual IDs, we could simply utilise strplit() function to split the IDs at the line break characters '\n',
>> webContent = strsplit ( webContent , '\n' ) webContent = 1×1019 prison cell assortment Columns 1 through 11 {'00745966'} {'00745090'} {'00745022'} ... Source: https://www.cdslab.org/matlab/notes/data-transfer/io/index.html
Post a Comment for "How to Read Dat File in Matlab Script"