Then far, nosotros have 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 than general efficient methods of code interaction with users.


Methods of data input/output in MATLAB

Let's begin with an example code that explains the meaning of input/output (I/O) in MATLAB,

                          a              =              0.1              ;              b              =              ane              ;              10              =              0.six              ;              y              =              a              *              exp              (              b              *              x              )                      

In the above lawmaking, a, b, ten are examples of input information to code, and y is an example of code output. In such cases as in the above, the input data is said to be hardcoded in the program.

Input data can be fed to a MATLAB program in four dissimilar ways,

  1. let the user answer questions in a dialog in MATLAB concluding window,
  2. permit the user provide input on the operating organization command line,
  3. let the user write input data in a graphical interface,
  4. let the user provide input data in a file.

There are ii major methods of information output,

  • writing to the terminal window, equally previously done using disp() function, or,
  • writing to an output file.

We have already extensively discussed printing output to the last window. Reading from and writing data to file is also piece of cake as we volition see here.

Input/output from MATLAB concluding window

We accept already introduced and used this method frequently in the past, via the MATLAB's congenital-in function input(). If we were to become the input data for the in a higher place lawmaking via the terminal window, an example arroyo would exist the following,

                          datain              =              input              (              'input [a,b,c]: '              );              a              =              datain              (              1              );              b              =              datain              (              two              );              ten              =              datain              (              3              );              y              =              a              *              exp              (              b              *              10              )                      
            input a,b,c: [0.one, 1, 0.6] y =     0.1822                      

One could also read the input values as cord ans so 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]: '              ,              's'              );              input              [              a              ,              b              ,              c              ]:              [              0.one              ,              1              ,              0.vi              ]              >>              class              (              datain              )                      
                          >>              datain              =              str2num              (              datain              )                      
            datain =     0.1000    1.0000    0.6000                      
                          >>              a              =              datain              (              i              );              >>              b              =              datain              (              ii              );              >>              x              =              datain              (              3              );              >>              y              =              a              *              exp              (              b              *              10              )                      

Input/output data from operating arrangement's command line

This approach is most popular in Unix-similar environments, where most users are accepted to using the Bash command line. Withal, it can be readily used in Windows cmd environment as well. For this approach, we have to invoke MATLAB from the computer operating organization'southward command line, that is, Bash in Linux systems, and cmd in Windows,

            start matlab              -nosplash              -nodesktop              -r              "testIO"                      

Then a MATLAB command-line window opens in your calculator like the following that runs automatically your code (stored in testIO.k).

In the above command, we are starting MATLAB from the OS command line with our own pick of optional arguments for MATLAB. You can specify startup options (too called command flags or control-line switches) that instruct the MATLAB programme to perform sure operations when you start it. On all platforms, specify the options every bit arguments to the MATLAB command when you get-go at the operating system prompt. For case, 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 current version of the software. A splash screen usually appears while a game or programme is launching),

The flag -nodesktop result in opening only the MATLAB command line, and no MATLAB Graphical user interface (GUI) simply similar the figure above. Finally, the flag -r executes the MATLAB file that appears correct after it, specified equally a string or as the name of a MATLAB script or function. If a MATLAB statement is MATLAB lawmaking, yous should enclose the string with double quotation marks. If a MATLAB statement is the name of a MATLAB office or script, do not specify the file extension and do not use quotation marks. Any required file must exist on the MATLAB search path or in the startup folder. You can also set up MATLAB's working folder right from the control-line using -sd flag. You can notice notice more information about all possible flags here. On Windows platforms, you can precede a startup option with either a hyphen (-) or a slash (/). For case, -nosplash and /nosplash are equivalent.

Annotation that you can too quote MATLAB on the Os command line, along with the name of the script you want to run. For example, suppose you wanted to run the original script,

                          a              =              0.i              ;              b              =              1              ;              10              =              0.6              ;              y              =              a              *              exp              (              b              *              10              )                      

Notwithstanding, now with a, b, x, given at runtime. Yous could write a script file test.m that contains,

and give the variables values at runtime, on Os command line, like the post-obit,

            matlab              -nosplash              -nodesktop              -r              "a = 0.i; b = 1; ten = 0.6; testIO"                      

The figure below shows a screen-shot illustrating the output of the higher up command.

Input/output information from a Graphical User Interface

This method of inputting data is done past constructing a Graphical User Interface (GUI) which opens and takes input from the user. This is probably one of the near convenient methods for users to input data. Yous can practise this in MATLAB for example by using the built-in function inputdlg() which creates a dialog box that gathers user input. But this method of information collection is across the scope of our course. More information about this tin can be found here.

Input/output information from file

In cases where the input/output data is big, the command-line arguments and input from the last window are non efficient anymore. In such cases, the most common arroyo is to let the code read/write data from a pre-existing file, the path to which is most often given to the code via the Bone command line or MATLAB terminal window.

There are many methods of importing and exporting data to and from MATLAB, only some of which nosotros volition hash out here. For more information run across hither, here, and here. The post-obit table shows some of the almost of import import functions in MATLAB, which we will discuss here as well.

Tabular array of Mutual Methods for Importing Information from a File to MATLAB.
Function Description
load() Load MATLAB variables from file into MATLAB workspace
save() save 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 information 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 information into a Microsoft Excel spreadsheet file
readtable() Create table from file
writetable() Write table to file
imread() Read epitome from graphics file
imwrite() Write prototype to graphics file
importdata() Load information from file
textscan() Read formatted information from text file or string
fgetl() Read line from file, removing newline characters
fread() Read information from binary file
fwrite() Write information to binary file
type() Display contents of file

Loading/saving MATLAB workspace variables

MATLAB has two useful functions that tin salve the workspace variables into special MATLAB .mat files, to be later load again into the aforementioned or another MATLAB workspace for further work or manipulation. The part salvage() saves workspace variables to a given file. The most useful options for this role are the following,

                          salve              (              filename              )              salve              (              filename              ,              variables              )              salvage              (              filename              ,              variables              ,              fmt              )                      
  • save(filename) saves all variables from the current workspace in a MATLAB formatted binary file chosen MAT-file with the given name filename. If the file filename exists, save() overwrites the file.
  • salve(filename,variables) saves but the variables or fields of a structure assortment specified by variables. For example,
                                      p                  =                  rand                  (                  i                  ,                  10                  );                  q                  =                  ones                  (                  ten                  );                  save                  (                  'pqfile.mat'                  ,                  'p'                  ,                  'q'                  )                              

    will create the binary MAT file pqfile.mat which contains the ii variables.

  • relieve(filename,variables,fmt) saves the requested variables with the file format specified by fmt. The variables statement is optional. If you do not specify variables, the relieve role saves all variables in the workspace. File format, specified as one of the post-obit. When using the command grade of save, you do not need to enclose the input in single or double quotes, for instance, save myFile.txt -ascii -tabs. For example,
                                      p                  =                  rand                  (                  1                  ,                  10                  );                  q                  =                  ones                  (                  10                  );                  salvage                  (                  'pqfile.txt'                  ,                  'p'                  ,                  'q'                  ,                  '-ascii'                  )                              

    will create an ASCII text file pqfile.txt which contains the two variables p and q.

Table of Common Methods for Importing Data from a File to MATLAB.
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 sixteen digits of precision.
'-ascii','-double','-tabs' Tab-delimited text format with sixteen digits of precision.

Similarly, i can reload the aforementioned files into MATLAB workspace over again if needed, for example using MATLAB load() function,

                          >>              load              (              'pqfile.txt'              )              >>              pqfile                      
            pqfile =   Columns 1 through 8     0.0975    0.2785    0.5469    0.9575    0.9649    0.1576    0.9706    0.9572     1.0000    1.0000    i.0000    1.0000    one.0000    1.0000    one.0000    i.0000     1.0000    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000    1.0000     ane.0000    1.0000    1.0000    one.0000    ane.0000    one.0000    i.0000    1.0000     1.0000    1.0000    i.0000    1.0000    1.0000    1.0000    1.0000    1.0000     one.0000    1.0000    ane.0000    1.0000    1.0000    1.0000    ane.0000    1.0000     1.0000    1.0000    i.0000    1.0000    1.0000    1.0000    1.0000    ane.0000     ane.0000    1.0000    1.0000    ane.0000    ane.0000    i.0000    one.0000    1.0000     i.0000    1.0000    one.0000    1.0000    one.0000    1.0000    1.0000    1.0000     1.0000    ane.0000    1.0000    1.0000    one.0000    ane.0000    ane.0000    1.0000     1.0000    ane.0000    1.0000    ane.0000    one.0000    i.0000    i.0000    ane.0000   Columns 9 through 10     0.4854    0.8003     1.0000    i.0000     1.0000    ane.0000     ane.0000    ane.0000     one.0000    one.0000     1.0000    1.0000     1.0000    1.0000     one.0000    1.0000     1.0000    i.0000     1.0000    1.0000     1.0000    1.0000                      

Only note that upon loading the Ascii file, the data about the private variables is lost. By contrast, loading data using the MAT file volition preserve the structure of the variables,

                          >>              load              (              'pqfile.mat'              )              >>              p                      
            p =   Columns ane through viii     0.1419    0.4218    0.9157    0.7922    0.9595    0.6557    0.0357    0.8491   Columns 9 through 10     0.9340    0.6787                      
            q =      ane     1     1     one     one     1     1     1     1     1      1     one     1     one     1     i     1     i     ane     1      ane     1     1     1     1     1     ane     1     ane     one      ane     1     1     one     1     i     one     1     1     1      1     1     1     1     one     one     1     1     1     1      1     1     1     i     one     1     1     1     one     1      1     1     1     1     ane     1     1     1     1     1      1     1     i     1     1     ane     1     ane     1     i      1     1     1     1     i     ane     1     1     i     one      ane     1     i     1     1     1     1     1     1     1                      

Reading/writing a formatted file using fscanf() and fprintf()

In that location are numerous methods of reading the contents of a file in MATLAB. The most trivial and probably to the lowest degree pleasing method is through MATLAB'south built-in office fscanf(). To read a file, say this file, yous volition have to first open up information technology in MATLAB,

                          fileID              =              fopen              (              'information.in'              ,              'r'              );              formatSpec              =              '%f'              ;              A              =              fscanf              (              fileID              ,              formatSpec              )              fclose              (              fileID              );                      

Note that dissimilar the C language'south fscanf(), in MATLAB fscanf() is vectorized significant that information technology can read multiple lines all at one time. Here, the attribute 'r' states that the file is opened to read information technology (vs writing, or some other purpose). A listing of available options for fopen() is the following,

Table of Attributes for MATLAB function fopen().
Attribute Description
'r' Open up 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 terminate 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 data to the cease of the file.
'A' Open up file for appending without automatic flushing of the electric current output buffer.
'West' Open up file for writing without automated flushing of the current output buffer.

The full general syntax for reading an array from an input file using fscanf() is the following,

                          array              =              fscanf              (              fid              ,              format              )              [              array              ,              count              ]              =              fscanf              (              fid              ,              format              ,              size              )                      

where the optional argument size specifies the amount of data to be read from the file. There are iii versions of this argument,

  • n: Reads exactly northward values. After this statement, array will be a column vector containing north values read from the file.
  • Inf: Reads until the finish of the file. After this statement, array will be a column vector containing all of the data until the stop of the file.
  • [north m]: Reads exactly, $n\times one thousand$ values, and format the data as an $n\times 1000$ assortment. For example, consider this file, which contains ii columns of numeric data. I could read this data using fscanf() like the following,
                                      >>                  formatSpec                  =                  '%d %f'                  ;                  >>                  sizeA                  =                  [                  2                  Inf                  ];                  >>                  fileID                  =                  fopen                  (                  'nums2.txt'                  ,                  'r'                  );                  >>                  A                  =                  transpose                  (                  fscanf                  (                  fileID                  ,                  formatSpec                  ,                  sizeA                  ))                  >>                  fclose                  (                  fileID                  );                              

    A = one.0000 2.0000 3.0000 4.0000 5.0000 0.8147 0.9058 0.1270 0.9134 0.6324

Now suppose you perform some on functioning on A, say the elemental multiplication of A by itself. Then you want to shop (append) the result into another file. Y'all tin practice this using MATLAB function fprintf(),

                          >>              formatSpec              =              '%d %f \n'              ;              >>              fileID              =              fopen              (              'nums3.txt'              ,              'w+'              );              >>              fprintf              (              fileID              ,              formatSpec              ,              A              .*              A              );              >>              fclose              (              fileID              );                      

The pick westward+ tells MATLAB to store the result in a file named num3.txt, and if the file does already exist, then suspend the result to the stop of the current existing file. To run across what formatting specifiers y'all tin can use with MATLAB fscanf() and fprintf(), come across this page.

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's manual or the web. For instance, consider this file which contains a set of temperature values in degrees (including the Celsius degrees symbol). I way to read this file and skipping the degrees symbol in MATLAB could exist then the following set 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 =      v                      

This method of reading a file is very powerful but rather detailed, low-level and cumbersome, especially that you take to define the format for the content of the file appropriately. Most oftentimes, other higher-level MATLAB's built-in function come to rescue us from the hassles of using fscanf(). For more data most this function though, if you really want to stick to information technology, come across here. Some important MATLAB special characters (escape characters) that can also appear in fprintf() are also given in the following tabular array.

Tabular array of escape characters in MATLAB.
Symbol Effect on Text
'' Single quotation marker
%% Single per centum sign
\\ Single backslash
\n New line
\t Horizontal tab
\v Vertical tab

Reading/writing data using dlmread()/dlmwrite() and csvread()/csvwrite()

The methods discussed above are rather primitive, in that they require a chip of effort 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 can handle a wide diversity of data file formats. Two of the nearly common functions are defended specifically to read data 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 data (numbers and text) in plain text format. Each line of the file is called a data tape and each tape consists of i or more fields, separated past commas. The use of the comma as a field separator is the source of the name for this file format.

Now suppose y'all wanted to read ii matrices whose elements were stored in CSV format in ii csv data files matrix1.csv and matrix2.csv. You can accomplish this task simply by calling MATLAB's born csv-reader office called csvread(filename). Hither the give-and-take filename is the path to the file in your local hard drive. For example, download these two given csv files above in your MATLAB working directory and so try,

                          >>              Mat1              =              csvread              (              'matrix1.csv'              );              >>              Mat2              =              csvread              (              'matrix2.csv'              );                      

And then suppose you want to multiply these 2 vectors and store the upshot in a new variable and write it to a new output CSV file. You could do,

                          Mat3              =              Mat1              *              Mat2              ;              >>              csvwrite              (              'matrix3.csv'              ,              Mat3              )                      

which would output this file: matrix3.csv for y'all.

Alternatively, you could also apply MATLAB'due south congenital-in functions dlmread() and dlmwrite() functions to do the same things as above. These two functions read and write ASCII-delimited file of numeric data. For example,

                          >>              Mat1              =              dlmread              (              'matrix1.csv'              );              >>              Mat2              =              dlmread              (              'matrix2.csv'              );              >>              Mat3              =              Mat1              *              Mat2              ;              >>              dlmwrite              (              'matrix3.dat'              ,              Mat3              );                      

Annotation that, dlmread() and dlmwrite() come with an optional argument delimiter of the following format,

                          >>              dlmread              (              filename              ,              delimiter              )              >>              dlmwrite              (              filename              ,              matrixObject              ,              delimiter              )                      

where the statement delimiter is the field delimiter graphic symbol, specified as a grapheme vector or cord. For example, in the to a higher place case, the delimiter is comma ','. In other cases, you could, for case, utilize white space ' ', or '\t' to specify a tab delimiter, and so on. For instance, y'all could have equally written,

                          >>              dlmwrite              (              'matrix4.dat'              ,              Mat3              ,              '\t'              );                      

to create a tab-delimited file named matrix4.dat.

Reading/writing information using xlsread() and xlswrite()

One time data becomes more complex than uncomplicated numeric matrices or vectors, so we need more than complex MATLAB functions for IO. An case of such a case is when yous have stored your information in a Microsoft Excel file. For such cases, you tin utilise xlsread(filename) to read the file specified by the input argument filename to this function. We will, afterwards, run into some instance usages of this function in homework. Similarly, you could write information into an excel file using xlswrite(). For example,

                          >>              values              =              {              1              ,              2              ,              3              ;              4              ,              five              ,              'ten'              ;              7              ,              8              ,              9              };              >>              headers              =              {              'Outset'              ,              '2nd'              ,              'Tertiary'              };              >>              xlswrite              (              'XlsExample.xlsx'              ,[              headers              ;              values              ]);                      

would create this Microsoft Excel file for you.

Reading/writing data using readtable() and writetable()

Some other important and highly useful set of MATLAB functions for IO are readtable() and writetable(). The function readtable() is used to read data into MATLAB in the class of a MATLAB tabular array data type. For example, y'all could read the same Excel file that we created in a higher place into MATLAB using readtable() instead of xlsread(),

                          >>              XlsTable              =              readtable              (              'XlsExample.xlsx'              )                      
            XlsTable =      First    2nd    Third     _____    ______    _____      1        2         'iii'       4        5         'x'       7        viii         'nine'                      

Reading and writing epitome files using imread() and imwrite()

MATLAB has a actually wide range of input/output methods of data. Nosotros have already discussed some of the almost useful IO approaches in the previous sections. For graphics files, still, none of the previous functions are useful. Suppose you wanted to import a jpg or png or some other type graphics file into MATLAB to further process it. For this purpose, MATLAB has the built-in function imread() which can read image from an input graphics file. For example, to read this image file in MATLAB, you could exercise,

                          >>              homer              =              imread              (              'homer.jpg'              );              >>              imshow              (              homer              )                      

to get the following effigy in MATLAB,

Now suppose you want to convert this effigy to black-and-white and save it as a new figure. Yous could exercise,

                          >>              homerBW              =              rgb2gray              (              homer              );              >>              imshow              (              homerBW              )              >>              imwrite              (              homerBW              ,              'homerBW.png'              );                      

to go this black and white version of the above image, now in png format (or in any format you may wish, that is also supported by MATLAB).

Reading a file using importdata()

Probably, the virtually general MATLAB function for information input is importdata(). This function can be used to import well-nigh any type of information and MATLAB is capable of automatically recognizing the correct format for reading the file, based on its extension and content. For example, yous could read the aforementioned epitome file higher up, using importdata(),

                          >>              newHomer              =              importdata              (              'homer.jpg'              );              >>              imshow              (              newHomer              )                      

to import information technology to MATLAB. At the aforementioned fourth dimension, you lot could also utilise it to import information from the excel file that we created higher up, XlsExample.xlsx,

                          >>              newXls              =              importdata              (              'XlsExample.xlsx'              )                      
            newXls =            data: [3x3 double]       textdata: {3x3 cell}     colheaders: {'Showtime'  'Second'  '3rd'}                      

or similarly, read a csv-delimited file like matrix3.csv,

                          >>              newMat3              =              importdata              (              'matrix3.csv'              )                      
            newMat3 =   Columns ane 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 eight through 10        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 full general, you can use importdata() to read MATLAB binary files (MAT-files), ASCII files and Spreadsheets, also 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 past line, removing the new line characters \n from the finish of each line. The unabridged line is read as a string. For example, consider this file. I could read the content of this text file using the function fgetl() like the following,

                          >>              fid              =              fopen              (              'text.txt'              );              >>              line              =              fgetl              (              fid              )              % read line excluding newline grapheme                      
            line = The main benefit of using a weakly-typed language is the ability to practise rapid prototyping. The number of lines of code required to declare and employ a dynamically allocated array in C (and properly clean upwardly after its use) is much greater than the number of lines required for the same process in MATLAB.                      
                          >>              line              =              fgetl              (              fid              )              % read line excluding newline character                      
                          >>              line              =              fgetl              (              fid              )              % read line excluding newline graphic symbol                      
            line = Weak typing is as well practiced for code-reuse. You can code a scalar algorithm in MATLAB and with relatively little try alter it to work on arrays equally 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 web using webread()

In today's earth, it oftentimes happens that the data 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 case, consider this folio on this course'due south website. It is indeed a text file containing a prepare of IDs for some astrophysical events. Suppose, y'all needed to read and store these IDs locally on your device. You could simply attempt the following lawmaking in MATLAB to fetch all of the tabular array's data in a unmarried 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'                      

Now if we wanted to go the individual IDs, we could simply use strplit() function to carve up the IDs at the line pause characters '\n',

                          >>              webContent              =              strsplit              (              webContent              ,              '\northward'              )                      
            webContent =   1×1019 cell assortment   Columns one through xi     {'00745966'}    {'00745090'}    {'00745022'} ...