So far, we accept indirectly discussed several methods of getting input information from the user, and several methods of outputting the result in a MATLAB program. This annotation attempts at formalizing all the previous discussions and introduce more general efficient methods of code interaction with users.


Methods of information input/output in MATLAB

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

                          a              =              0.1              ;              b              =              1              ;              ten              =              0.half-dozen              ;              y              =              a              *              exp              (              b              *              x              )                      

In the above lawmaking, a, b, ten are examples of input data to code, and y is an instance of code output. In such cases equally 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 different ways,

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

At that place are two major methods of data output,

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

We have already extensively discussed printing output to the terminal window. Reading from and writing data to file is as well easy as we will see here.

Input/output from MATLAB terminal window

Nosotros have already introduced and used this method ofttimes in the past, via the MATLAB's born office input(). If we were to get the input data for the higher up code via the last window, an example arroyo would be the following,

                          datain              =              input              (              'input [a,b,c]: '              );              a              =              datain              (              1              );              b              =              datain              (              two              );              x              =              datain              (              3              );              y              =              a              *              exp              (              b              *              x              )                      
            input a,b,c: [0.1, one, 0.6] y =     0.1822                      

One could also read the input values as string ans then convert them to real values or parse the input using i of MATLAB's built-in functions, for example,

                          >>              datain              =              input              (              'input [a,b,c]: '              ,              's'              );              input              [              a              ,              b              ,              c              ]:              [              0.one              ,              1              ,              0.6              ]              >>              course              (              datain              )                      
                          >>              datain              =              str2num              (              datain              )                      
            datain =     0.1000    1.0000    0.6000                      
                          >>              a              =              datain              (              one              );              >>              b              =              datain              (              2              );              >>              x              =              datain              (              three              );              >>              y              =              a              *              exp              (              b              *              ten              )                      

Input/output data from operating organisation's command line

This approach is virtually popular in Unix-like environments, where most users are accustomed to using the Fustigate command line. However, it can be readily used in Windows cmd environment besides. For this approach, we have to invoke MATLAB from the computer operating system'southward command line, that is, Bash in Linux systems, and cmd in Windows,

            offset matlab              -nosplash              -nodesktop              -r              "testIO"                      

And so a MATLAB command-line window opens in your figurer similar the following that runs automatically your lawmaking (stored in testIO.chiliad).

In the above control, nosotros are starting MATLAB from the Bone command line with our own choice of optional arguments for MATLAB. You can specify startup options (also called command flags or command-line switches) that instruct the MATLAB program to perform certain operations when you start it. On all platforms, specify the options every bit arguments to the MATLAB command when y'all get-go at the operating system prompt. For example, 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 consequence in opening merely the MATLAB control line, and no MATLAB Graphical user interface (GUI) just like the effigy above. Finally, the flag -r executes the MATLAB file that appears correct afterward information technology, specified as a string or as the name of a MATLAB script or function. If a MATLAB argument is MATLAB lawmaking, you should enclose the cord with double quotation marks. If a MATLAB statement is the name of a MATLAB part or script, exercise not specify the file extension and do non employ quotation marks. Whatever required file must exist on the MATLAB search path or in the startup binder. You can also gear up MATLAB'south working binder right from the command-line using -sd flag. Y'all tin can find find more information about all possible flags here. On Windows platforms, you tin can precede a startup choice with either a hyphen (-) or a slash (/). For example, -nosplash and /nosplash are equivalent.

Note that you can also quote MATLAB on the OS command line, along with the name of the script yous want to run. For example, suppose you wanted to run the original script,

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

All the same, 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 = ane; x = 0.6; testIO"                      

The figure beneath 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 past 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 information. You can practice this in MATLAB for case by using the built-in role inputdlg() which creates a dialog box that gathers user input. Just this method of information collection is beyond the telescopic of our class. More information about this tin be plant hither.

Input/output data from file

In cases where the input/output data 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 most often given to the code via the Os command line or MATLAB terminal window.

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

Table of Common Methods for Importing Information from a File to MATLAB.
Function Description
load() Load MATLAB variables from file into MATLAB workspace
save() relieve MATLAB variables from MATLAB workspace into a MATLAB `.mat` file.
fscanf() Read information from text file
fprintf() Write information 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 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 epitome to graphics file
importdata() Load information 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
type() Brandish 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 another MATLAB workspace for farther work or manipulation. The function relieve() saves workspace variables to a given file. The most useful options for this function are the following,

                          save              (              filename              )              save              (              filename              ,              variables              )              save              (              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.
  • relieve(filename,variables) saves merely the variables or fields of a structure array specified by variables. For example,
                                      p                  =                  rand                  (                  one                  ,                  ten                  );                  q                  =                  ones                  (                  x                  );                  save                  (                  'pqfile.mat'                  ,                  'p'                  ,                  'q'                  )                              

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

  • save(filename,variables,fmt) saves the requested variables with the file format specified by fmt. The variables argument is optional. If yous do not specify variables, the salvage function saves all variables in the workspace. File format, specified equally ane of the post-obit. When using the command course of save, y'all do not demand to enclose the input in single or double quotes, for example, save myFile.txt -ascii -tabs. For instance,
                                      p                  =                  rand                  (                  one                  ,                  10                  );                  q                  =                  ones                  (                  10                  );                  save                  (                  'pqfile.txt'                  ,                  'p'                  ,                  'q'                  ,                  '-ascii'                  )                              

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

Table of Common Methods for Importing Information from a File to MATLAB.
Value of fmt File Format
'-mat' Binary MAT-file format.
'-ascii' Text format with viii digits of precision.
'-ascii','-tabs' Tab-delimited text format with eight digits of precision.
'-ascii','-double' Text format with 16 digits of precision.
'-ascii','-double','-tabs' Tab-delimited text format with xvi digits of precision.

Similarly, one can reload the same files into MATLAB workspace once again if needed, for case using MATLAB load() function,

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

But notation that upon loading the Ascii file, the data about the private variables is lost. By contrast, loading data using the MAT file will preserve the construction of the variables,

                          >>              load              (              'pqfile.mat'              )              >>              p                      
            p =   Columns one through 8     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 =      i     one     ane     1     i     ane     1     1     1     one      i     1     ane     1     1     i     one     1     i     ane      1     1     1     i     one     ane     1     i     ane     ane      1     one     1     1     1     ane     1     1     1     i      i     1     i     one     1     1     1     ane     1     one      1     1     1     ane     1     1     i     1     ane     1      one     one     1     one     1     ane     1     1     1     one      1     ane     1     1     1     one     1     1     ane     ane      one     1     i     1     1     i     1     one     1     one      one     1     ane     1     i     1     one     1     1     1                      

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

There are numerous methods of reading the contents of a file in MATLAB. The nearly trivial and probably least pleasing method is through MATLAB'south built-in function fscanf(). To read a file, say this file, you will take to first open information technology in MATLAB,

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

Notation that unlike the C linguistic communication'south fscanf(), in MATLAB fscanf() is vectorized pregnant that it tin read multiple lines all at once. Here, the attribute 'r' states that the file is opened to read it (vs writing, or some other purpose). A list of available options for fopen() is the post-obit,

Tabular array of Attributes for MATLAB role fopen().
Attribute Description
'r' Open file for reading.
'west' Open up or create new file for writing. Discard existing contents, if whatsoever.
'a' Open up or create new file for writing. Append data to the cease of the file.
'r+' Open up file for reading and writing.
'west+' Open or create new file for reading and writing. Discard existing contents, if whatever.
'a+' Open or create new file for reading and writing. Suspend data to the end of the file.
'A' Open file for appending without automated flushing of the current output buffer.
'Westward' Open file for writing without automatic flushing of the electric current output buffer.

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

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

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

  • n: Reads exactly n values. After this statement, array volition exist a column vector containing n values read from the file.
  • Inf: Reads until the end of the file. After this statement, array will be a column vector containing all of the data until the end of the file.
  • [n thou]: Reads exactly, $n\times thou$ values, and format the information every bit an $north\times m$ array. For example, consider this file, which contains 2 columns of numeric data. One could read this data using fscanf() similar the post-obit,
                                      >>                  formatSpec                  =                  '%d %f'                  ;                  >>                  sizeA                  =                  [                  ii                  Inf                  ];                  >>                  fileID                  =                  fopen                  (                  'nums2.txt'                  ,                  'r'                  );                  >>                  A                  =                  transpose                  (                  fscanf                  (                  fileID                  ,                  formatSpec                  ,                  sizeA                  ))                  >>                  fclose                  (                  fileID                  );                              

    A = one.0000 2.0000 iii.0000 four.0000 5.0000 0.8147 0.9058 0.1270 0.9134 0.6324

Now suppose yous perform some on operation on A, say the elemental multiplication of A by itself. And so you lot want to shop (append) the event into some other file. You can do this using MATLAB function fprintf(),

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

The choice due west+ tells MATLAB to shop the result in a file named num3.txt, and if the file does already exist, then append the consequence to the terminate of the current existing file. To run into what formatting specifiers you can use 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 actually details that are specific to your needs and the best approach is to seek the solution to your specific trouble by searching MATLAB's manual or the web. For example, consider this file which contains a gear up of temperature values in degrees (including the Celsius degrees symbol). One way to read this file and skipping the degrees symbol in MATLAB could exist and so the post-obit gear 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 =      5                      

This method of reading a file is very powerful but rather detailed, depression-level and cumbersome, particularly that you lot take to define the format for the content of the file appropriately. Virtually often, other college-level MATLAB's born office come to rescue us from the hassles of using fscanf(). For more than information virtually this function though, if you really want to stick to it, see here. Some important MATLAB special characters (escape characters) that can also appear in fprintf() are also given in the following table.

Table of escape characters in MATLAB.
Symbol Effect on Text
'' Single quotation mark
%% Single per centum sign
\\ Single backslash
\northward New line
\t Horizontal tab
\five Vertical tab

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

The methods discussed in a higher place are rather archaic, in that they require a bit of try by the user to know something about the structure of the file and its format. MATLAB has a long list of advanced IO functions that tin can handle a broad multifariousness of data file formats. Two of the most mutual 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 type 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 record consists of one or more fields, separated past commas. The employ of the comma as a field separator is the source of the name for this file format.

Now suppose y'all wanted to read 2 matrices whose elements were stored in CSV format in two csv information files matrix1.csv and matrix2.csv. You can attain this task just by calling MATLAB's built-in csv-reader function called csvread(filename). Here the word 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 then try,

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

And then suppose y'all want to multiply these two vectors and store the result in a new variable and write information technology 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 use MATLAB'due south built-in functions dlmread() and dlmwrite() functions to do the same things as above. These ii 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              );                      

Note that, dlmread() and dlmwrite() come with an optional statement delimiter of the post-obit format,

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

where the statement delimiter is the field delimiter character, specified as a grapheme vector or string. For instance, in the above example, the delimiter is comma ','. In other cases, you could, for example, use white space ' ', or '\t' to specify a tab delimiter, and then on. For example, you could have equally written,

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

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

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

Once information becomes more circuitous than simple numeric matrices or vectors, then we demand more complex MATLAB functions for IO. An instance of such a case is when y'all take stored your information in a Microsoft Excel file. For such cases, you can apply xlsread(filename) to read the file specified past the input argument filename to this part. We will, later on, run across 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              ,              5              ,              'x'              ;              vii              ,              8              ,              9              };              >>              headers              =              {              'Commencement'              ,              '2nd'              ,              'Third'              };              >>              xlswrite              (              'XlsExample.xlsx'              ,[              headers              ;              values              ]);                      

would create this Microsoft Excel file for you lot.

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

Another important and highly useful set of MATLAB functions for IO are readtable() and writetable(). The part readtable() is used to read information into MATLAB in the course of a MATLAB table information type. For example, you could read the aforementioned Excel file that we created above into MATLAB using readtable() instead of xlsread(),

                          >>              XlsTable              =              readtable              (              'XlsExample.xlsx'              )                      
            XlsTable =      Start    Second    Third     _____    ______    _____      1        ii         'three'       four        5         'ten'       vii        viii         '9'                      

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

MATLAB has a actually wide 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 you wanted to import a jpg or png or another type graphics file into MATLAB to farther process it. For this purpose, MATLAB has the congenital-in function imread() which can read image from an input graphics file. For example, to read this image file in MATLAB, you could do,

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

to get the post-obit figure in MATLAB,

Now suppose you desire to convert this figure to black-and-white and save information technology equally a new effigy. Y'all could do,

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

to go this black and white version of the to a higher place epitome, now 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 function for data input is importdata(). This function tin be used to import almost any blazon of information 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 image file above, using importdata(),

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

to import it to MATLAB. At the same time, yous could as well use information technology to import information from the excel file that we created to a higher place, XlsExample.xlsx,

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

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 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 general, y'all tin apply importdata() to read MATLAB binary files (MAT-files), ASCII files and Spreadsheets, equally well equally images and audio files.

Reading a file using fgetl()

Another useful MATLAB function 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 end of each line. The entire line is read every bit a string. For example, consider this file. 1 could read the content of this text file using the office fgetl() like the post-obit,

                          >>              fid              =              fopen              (              'text.txt'              );              >>              line              =              fgetl              (              fid              )              % read line excluding newline character                      
            line = The main 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 subsequently its use) is much greater than the number of lines required for the aforementioned process in MATLAB.                      
                          >>              line              =              fgetl              (              fid              )              % read line excluding newline grapheme                      
                          >>              line              =              fgetl              (              fid              )              % read line excluding newline grapheme                      
            line = Weak typing is also good for lawmaking-reuse. You can lawmaking a scalar algorithm in MATLAB and with relatively little effort modify it to work on arrays as well equally scalars. The fact that MATLAB is a scripted instead of a compiled language besides contributes to rapid prototyping.                      

Reading information from web using webread()

In today's world, information technology often happens that the data you need for your research is already stored somewhere on the world-broad-web. For such cases, MATLAB has built-in methods and functions to read and import data or even a webpage. For example, consider this folio on this course's website. It is indeed a text file containing a set of IDs for some astrophysical events. Suppose, you needed to read and store these IDs locally on your device. You could simply try the following code in MATLAB to fetch all of the table'southward 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 get the individual IDs, we could simply utilize strplit() role to split the IDs at the line break characters '\n',

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