Chapter 11 Input/Output (I/O) Functions

Size: px
Start display at page:

Download "Chapter 11 Input/Output (I/O) Functions"

Transcription

1 EGR115 Introduction to Computing for Engineers Input/Output (I/O) Functions from: S.J. Chapman, MATLAB Programming for Engineers, 5 th Ed Cengage Learning Topics Introduction: MATLAB I/O 11.1 The textread Function 11.2 More about the load & save Commands 11.3 An Introduction to MATLAB File Processing 11.4 File Opening & Closing 11.5 Binary I/O Functions 11.6 Formatted I/O Functions 11.7 Comparing Formatted & Binary I/O Functions

2 Slide 1 of 17 Introduction: MATLAB I/O MATLAB I/O In chapter 2, we learned how to load (input) and save MATLAB data using the load and save commands, and how to write out (display output at command window) using fprinf command. In this chapter, we will learn more about MATLAB s Input/Output (I/O) capabilities: Reading text data from a file: textread and textscan commands More about load and save commands Other MATLAB I/O options File Input/Output in MATLAB In addition to the text I/O (between the disk and MATLAB workspace), MATLAB can open the file, read from or write to the file, and close the file. Open the file: fid = fopen(filename, r ); fid = fopen(filename, w ); (permission = r or w tells MATLAB that we want to read from or write to the file) Read from the file; a = fscanf(fid,format,size); Write to the file: fprintf(fid,format,variables); Close the file: fclose(fid);

3 Slide 2 of /11.2 The textread Function More about the load & save Commands MATLAB textread Function (see EXAMPLE 5-6) In MATLAB, the textread function reads text files that are formatted into columns of data, where each column can be of different type, and stores the contents of each column in a separate output array. [a,b,c,...] = textread(filename,format,n) MATLAB save/load Command In MATLAB, the save command saves workplace data to disk, and the load command loads data from disk into workspace. save filename [content] [options] load filename [options] [content] load Command Options The textread command reads text files that are formatted into columns of data (Example 5-6). Editor [first,last,blood,gpa,age,answer] =... textread('test_input.dat','%s %s %s %f %d %s') >> example_5_6.m first = James Sally last = Jones Smith blood = O+ A+ gpa = age = answer = Yes No Command Window The textread command can also skip selected columns by adding an asterisk to the corresponding format descriptor (for example, %*s). Editor [first,last,blood,gpa,age,answer] =... textread('test_input.dat','%s %s %*s %f %*d %*s') >> example_5_6.m first = James Sally last = Jones Smith gpa = Command Window

4 Slide 3 of /11.2 The textread Function More about the load & save Commands load Command Contents load Command Options The save command saves MATLAB workspace data to disk, and the load command loads data from disk into the workspace. save filename [content] [options] load filename [options] [content] The MAT and ASCII Files -mat MAT files are MATLAB default file format files. MAT files preserve all of the information about each variable in the workspace, including its class, name, and whether or not it is global. MAT files are unique to MATLAB and cannot be used to share data with other programs. If the file name and the names of the variables to be loaded or saved are in strings, then it is necessary to require file name input from the user: filename = input( Enter save file name:, s ); save(filename, -mat ); -ascii This is American Standard Code for Information Exchange (ASCII) standard and can be used to share data between MATLAB and other programs. The save -ascii command will not save cell or structure array data, and it converts string data to numbers before saving it. The load -ascii command will only load space or tab separated data with an equal number of elements on each row, and it will place all of the data into a single variable with the same name as the input file.

5 11.3 An Introduction to MATLAB File Processing Slide 4 of 17 MATLAB Input/Output Functions The fopen Function fid = fopen(filename, permission, format) filename: is a string specifying the name of the file to open permission: is a character string specifying the mode in which the file is opened format: is an optional string specifying the numeric format of the data in the file Examples of fopen Functions (Case 1) Opening a Text File for Data Reading The command below opens a text file named example.dat for data reading. fid = fopen( example.dat, r ) The permission string is r, indicating that the file is to be opened for reading only. (Case 2) Opening a Text File for Data Writing The command below open a binary file named outdat for data writing. fid = fopen( outdat, wt ) or fid = fopen( outdat, at ) The wt permissions string specifies that the file is a new text file; if it already exists, then the old file will be deleted and a new empty file will be opened for writing. The at permissions string specifies that we want to append to an existing text file.

6 Slide 5 of File Opening & Closing fopen File Permissions fopen Numeric Format Strings Examples of fopen Functions (continued) (Case 3) Opening an Existing Binary File for Read/Write Access The command below opens a binary file named junk for data reading/writing. fid = fopen( junk, r+ ) fid = fopen( junk, w+ ) The permission strings r+ and w+ indicate that the existing files are opened and available for reading and writing accesses. Read/Write to the Open File (Text Files) Read from the file; a = fscanf(fid,format,size); Write to the file: fprintf(fid,format,variables); The fclose Function status = fclose(fid) status = fclose( all ) fid: is the file ID status: is the result of the operation (if the operation is successful, status will be 0, and if it is unsuccessful, status will be 1)

7 Slide 6 of Binary I/O Functions MATLAB Precision Strings The fwrite Function The fwrite function writes binary data in a user-specified format to a file. count = fwrite(fid,array,precision) array: is the array of values to write out count: the number of values written to the file MATLAB writes out data in column order, which means that the entire first column is written out, followed by the entire second column, and so forth. 1 2 array = [ 3 4] will be written out in the order of: 1, 3, 5, 2, 4, The fread Function The fread function reads binary data in a user-specified format from a file, and returns the data in a (possibly different) user-specified format. [array,count] = fread(fid,size,precision) size: is the number of values to read precision: specifies both the format of the data on the disk and the format of the data array to be returned to the calling program. The general form of the precision string is: disk_precision=>array_precision single single=>single *single double=>real*4 Reads data in single precision format from disk and returns it in a double array Reads data in single precision format from disk and returns it in a single array Reads data in single precision format from disk and returns it in a single array (a shorthand version) Reads data in double precision format from disk and returns it in a single array

8 Slide 7 of Binary I/O Functions EXAMPLE 11-1 Develop a MATLAB script that creates an array containing 10,000 random values, opens a user-specified file for writing only, writes the array to disk in 64-bit floating-point format, and closes the file. Then, make the MATLAB script open the file for reading and read the data back into a array. >> binary_io Enter file name: testfile values written values read... binary_io.m % Script file: binary_io.m Editor % Prompt for file name filename = input('enter file name: ','s'); % Generate the data array out_array = randn(1,10000); % Open the output file for writing. [fid,msg] = fopen(filename,'w'); % Was the open successful? if fid > 0 % Write the output data. count = fwrite(fid,out_array,'float64'); % Tell user disp([int2str(count) ' values written...']); % Close the file status = fclose(fid); else % Output file open failed. Display message. disp(msg); end % Now try to recover the data. Open the file for reading. [fid,msg] = fopen(filename,'r'); % Was the open successful? if fid > 0 % Read the input data. [in_array, count] = fread(fid,[ ],'float64'); % Tell user disp([int2str(count) ' values read...']); % Close the file status = fclose(fid); else % Input file open failed. Display message. disp(msg); end (NOTE) You cannot open binary files in notepad (need a special software, such as: Binary Viewer)

9 Slide 8 of Binary I/O Functions Do-It-Yourself (DIY) EXERCISE 11-1 (a) Answer the following questions: 1. Why is the textread function especially useful for reading data created by programs written in other languages? 2. What are the advantages and disadvantages of saving data in a MAT file? 3. What MATLAB functions are used to open and close files? What is the difference between opening a binary file and opening a text file? (b) Examine the following MATLAB statements. Are they correct? If they are in error, specify what is wrong with them. 1. fid = fopen( file1, rt ); array = fread(fid,inf); fclose(fid); 2. fid = fopen( file1, w ); x = 1:10; count = fwrite(fid,x); fclose(fid); fid = fopen( file1, r ); array = fread(fid,[2 Inf]); fclose(fid); (a) 1. The textread function reads text files that are formatted into columns of data, where each column can be of a different type, and stores the contents of each column in a separate output array. This function is very useful for importing tables of data printed out (written in ASCII format) by other software applications. 2. MAT files are MATLAB default and efficient, as long as you use MATLAB as your programming language platform. MAT files preserve all of the information about each variable in the workspace, including its class, name, and whether or not it is global. MAT files can be compressed to save disk data space. MAT files preserve full precision of all variables. MAT files are, however, unique to MATLAB and cannot be used to share data with other programs. 3. MATLAB functions fopen and fclose can be used for opening and closing the file. Text files need to have file extension.dat while binary files do not have any file extension. For text files, fscanf and fprintf functions will be used; while binary files use fwrite and fread functions. (b) 1. Incorrect: opening a file as a text file, but reading the data in binary format (use fscanf). 2. Correct: creating a 10-element array x, opening a binary output file file1, writing the array to the file, and closing file. Next, opening the file again for reading, and reading the data into array array in a [2 Inf] format. The result is: array = [ ]

10 Slide 9 of Formatted I/O Functions fprintf Format Conversion Specifier The MATLAB fprintf Command The MATLAB fprintf command writes (or displays) formatted data in a user-specified format to a file (or on Command Window). The syntax is: count = fprintf(fid,format,val1,val2,...) fprintf(format,val1,val2,...) format: is the format string controlling the appearance of the data. count: the number of values written to the file If fid is not specified, the data will be written to the standard output device (default is the display on Command Window; this is what you have been doing so far!).

11 Slide 10 of Formatted I/O Functions fprintf Format Flags fprintf Escape Characters Understanding fprintf Format Marker (the very first % ): marks the beginning of the format. If the ordinary % character is to be printed out, then it must appear in the format string as %%. Modifier (minus sign <= NOTE: does NOT mean minus sign added but LEFT-JUSTIFY, plus sign <= added redundant plus sign for positive value, or padded zero <= added redundant leading zero): will be optional modifier (format flag). Field Width: will specify the field width of data. If not specified, MATLAB will set the default field width. Precision: will specify the minimum number of significant digit to display. If not specified, MATLAB will set the default field width. Format Descriptor (c, d, e,... x): will set the description of the data format type (Format Conversion Specifier). This (together with the Marker, the very first % ) is required as a minimum for fprintf command. Escape Characters: in addition to ordinary characters and formats, certain special characters can be used in a format string (adding new line, tab, carriage return, etc.) in fprintf.

12 Slide 11 of Formatted I/O Functions fprintf Examples fprintf( %e\n,123.4) e+002 Case 1: Displaying Decimal Data fprintf( %d\n,123) 123 fprintf( %6d\n,123) 123 fprintf( %6.4d\n,123) 0123 fprintf( %-6.4d\n,123) 0123 fprintf( %+6.4d\n,123) fprintf Examples Case 1: Displaying Decimal Data Display default decimal notation (%d) of a value (123) Display decimal notation with field width 6 (%6d) of a value (123) Display decimal notation with field width 6 and precision 4 (%6.4d) of a value (123) Display decimal notation, left justified, with field width 6 and precision 4 (%-6.4d) of a value (123) Display decimal notation, added leading plus sign, with field width 6 and precision 4 (%+6.4d) of a value (123)

13 Slide 12 of Formatted I/O Functions Case 2: Displaying Floating-Point Data fprintf( %f\n,123.4) fprintf( %8.2f\n,123.4) fprintf( %6.2f\n,123.4) fprintf( %10.2e\n,123.4) fprintf( %10.2E\n,123.4) e E+002 fprintf Examples (continued) Case 2: Displaying Floating-Point Data Display default floating-point notation (%f) of a value (123.4) Display floating-point notation with field width 8 and precision 2 (%8.2f) of a value (123.4) Display floating-point notation with field width 4 and precision 3 (%4.2f) of a value (123.4) Display exponential notation with field width 10 and precision 2 (%10.2e) of a value (123.4) using lower case e Display exponential notation with field width 10 and precision 2 (%10.2E) of a value (123.4) using upper case E

14 Slide 13 of Formatted I/O Functions Case 3: Displaying Character Data fprintf( %c\n, s ) s fprintf( %s\n, string ) string fprintf( %8s\n, string ) string fprintf( %-8s\n, string ) string fprintf Examples (continued) Case 3: Displaying Character Data Display default single character (%c) of a character ( s ) Display default string of characters (%s) of a character string ( string ) Display string of characters with field width 8 (%8s) of a character string ( string ) Display string of characters, left justified, with field width 8 (%-8s) of a character string ( string )

15 Slide 14 of Formatted I/O Functions EXAMPLE 11-2 Develop a MATLAB script that generates and prints a table of data (the square roots, squares, and cubes of all integers between 1 to 10). >> table Table of Square Roots, Squares, and Cubes Number Square Root Square Cube ====== =========== ====== ==== create_table.m % Script file: create_table.m Editor % Print the title of the table. fprintf(' Table of Square Roots, Squares, and Cubes\n\n'); % Print column headings fprintf(' Number Square Root Square Cube\n'); fprintf(' ====== =========== ====== ====\n'); % Generate the required data ii = 1:10; square_root = sqrt(ii); square = ii.^2; cube = ii.^3; % Create the output array out = [ii' square_root' square' cube']; % Print the data for ii = 1:10 fprintf (' %2d %11.4f %6d %8d\n',out(ii,:)); end

16 The MATLAB sprintf Command The MATLAB sprintf command writes formatted data to a character string (instead of a file). The syntax is: string = sprintf(fid, format,val1,val2,...) format: is the format string controlling the appearance of the data. fid: is the ID of a file to which the data will be written. The MATLAB fscanf Command The MATLAB fscanf command reads formatted data in a user-specified format from a file. The syntax is: array = fscanf(fid,format) [array,count] = fscanf(fid,format,size) format: is the format string controlling how the data is read. fid: is the ID of a file to which the data will be read. array: is the array that receives the data. count: returns the number of values read from the file. The optional argument size specifies the amount of data to be read from the file: n Read exactly n values. After this statement, array will be a column vector containing n values read from the file. inf Read 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,m] Read exactly n by m values, and format the data as an n by m array.

17 Formatted Files (Text Files) The MATLAB formatted I/O operations produce formatted files. A formatted file contains recognizable characters, numbers, and so forth that are stored as ordinary text. These files are easy to distinguish, because we can see the characters and numbers in the file when we display them on the screen or print them out. It can usually be moved between different types of computers with different internal data representations (Windows, Linux, Mac O/S, etc.) However, to use data in a formatted file, MATLAB must translate the characters in the file into the internal data format used by the computer. Unformatted Files (Binary Files) Unformatted files simply copy the information from the computer s memory directly to the disk file with no conversions at all. Since no conversions occur, no computer time is wasted formatting the data. However, data cannot be examined and interpreted directly by humans. In addition, it is usually cannot be moved between different types of computers with different internal data representations (Windows, Linux, Mac O/S, etc.)

18 Slide 17 of Comparing Formatted & Binary I/O Functions Do-It-Yourself (DIY) EXERCISE 11-2 (a) Answer the following questions: 1. What is the difference between unformatted (binary) and formatted I/O operations? 2. When should formatted I/O be used? When should unformatted I/O be used? (b) Examine the following MATLAB statements. Are they correct? If they are in error, specify what is wrong with them. 1. a = 2*pi; b = 6; c = hello ; fprintf(fid, %s %d %g\n,a,b,c); 2. data1 = 1:20; data2 = 1:20; fid = fopen( xxx, w+ ); fwrite(fid,data1); fprintf(fid, %g\n,data2); (a) 1. Unformatted (binary) data is simply a copy of the information from the computer s memory directly to the disk file with no conversions at all. Since no conversions occur, no computer time is wasted formatting the data. Formatted (text) data, on contrary, is a data file containing recognizable characters, numbers, and so forth that are stored as ordinary text. These files are easy to distinguish, because we can see the characters and numbers in the file when we display them on the screen or print them out. 2. Formatted I/O should be used to create formatted (text) files, in order to freely move (transport) data files between different types of computers with different internal data representations (Windows, Linux, Mac O/S, etc.). Unformatted I/O should be used to create unformatted (binary) files, to be used within a single computer that will not require file transfer with external computers (files only used within a computer with a single consistent internal data representations). (b) 1. Incorrect. The %s descriptor must correspond to a character string. The %g descriptor must not correspond to a character string. 2. Technically correct, but undesirable. It is possible to mix unformatted (binary) and formatted (text) data in a single file, but the file is then very hard to use for any purpose. Binary and text data should be written to separate files.

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB Fö 6: Filhantering DN1212 Numeriska metoder och grundläggande programmering paherman@kth.se KTH/CB 22 februari Pawel 2013Herman Lecture outline Recapitulation of what we already know about I/O Matlab format

More information

CSE 123. Lecture 9. Formatted. Input/Output Operations

CSE 123. Lecture 9. Formatted. Input/Output Operations CSE 123 Lecture 9 Formatted Input/Output Operations fpintf function writes formatted data in a user specified format to a file fid fprintf Function Format effects only the display of variables not their

More information

ES 117. Formatted Input/Output Operations

ES 117. Formatted Input/Output Operations ES 117 Formatted Input/Output Operations fpintf function writes formatted data in a user specified format to a file fid fprintf Function Format effects only the display of variables not their values through

More information

Importing and Exporting Data

Importing and Exporting Data Class14 Importing and Exporting Data MATLAB is often used for analyzing data that was recorded in experiments or generated by other computer programs. Likewise, data that is produced by MATLAB sometimes

More information

Access to Delimited Text Files

Access to Delimited Text Files Access to Delimited Text Files dlmread(filename, delimiter) reads ASCII-delimited file of numeric data. dlmwrite(filename, M, delimiter) writes the array M to the file using the specified delimiter to

More information

Singular Value Decomposition (SVD) 1

Singular Value Decomposition (SVD) 1 Singular Value Decomposition (SVD) 1 Let A m n be a matrix. Then σ is called one singular value associated with the singular vectors u R m 1 and v R n 1 for A provided that { Av = σu, A T u = σv. We further

More information

Using files. Computer Programming for Engineers (2014 Spring)

Using files. Computer Programming for Engineers (2014 Spring) Computer Programming for Engineers (2014 Spring) Using files Hyoungshick Kim Department of Computer Science and Engineering College of Information and Communication Engineering Sungkyunkwan University

More information

Matlab Programming Arrays and Scripts 1 2

Matlab Programming Arrays and Scripts 1 2 Matlab Programming Arrays and Scripts 1 2 Mili I. Shah September 10, 2009 1 Matlab, An Introduction with Applications, 2 nd ed. by Amos Gilat 2 Matlab Guide, 2 nd ed. by D. J. Higham and N. J. Higham Matrix

More information

MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass

MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass MATLAB User-defined functions, Data Input/Output Edited by Péter Vass User-defined functions Although, MATLAB provides a wide range of built-in functions it may often be necessary to create and use an

More information

ENG Introduction to Engineering

ENG Introduction to Engineering GoBack ENG 100 - Introduction to Engineering Lecture # 9 Files, Sounds, Images and Movies Koç University ENG 100 - Slide #1 File Handling MATLAB has two general ways of importing/exporting data from the

More information

Lecture 7. MATLAB and Numerical Analysis (4)

Lecture 7. MATLAB and Numerical Analysis (4) Lecture 7 MATLAB and Numerical Analysis (4) Topics for the last 2 weeks (Based on your feedback) PDEs How to email results (after FFT Analysis (1D/2D) Advanced Read/Write Solve more problems Plotting3Dscatter

More information

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400 1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400 American Standard Code for Information Interchange (ASCII) 2 Everything in the computer is encoded in binary.

More information

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009)

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009) 5. MATLAB I/O 1 Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, 2017 The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009) Topics Loading and Saving the Workspace File Access Plo$ng

More information

MATLAB Introduction to MATLAB Programming

MATLAB Introduction to MATLAB Programming MATLAB Introduction to MATLAB Programming MATLAB Scripts So far we have typed all the commands in the Command Window which were executed when we hit Enter. Although every MATLAB command can be executed

More information

Programming in Mathematics. Mili I. Shah

Programming in Mathematics. Mili I. Shah Programming in Mathematics Mili I. Shah Starting Matlab Go to http://www.loyola.edu/moresoftware/ and login with your Loyola name and password... Matlab has eight main windows: Command Window Figure Window

More information

Worksheet 6. Input and Output

Worksheet 6. Input and Output Worksheet 6. Input and Output Most programs (except those that run other programs) contain input or output. Both fortran and matlab can read and write binary files, but we will stick to ascii. It is worth

More information

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program CMPT 102 Introduction to Scientific Computer Programming Input and Output Janice Regan, CMPT 102, Sept. 2006 0 Your first program /* My first C program */ /* make the computer print the string Hello world

More information

12-Reading Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

12-Reading Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie 12-Reading Data text: Chapter 4.4-4.5 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie Overview Reading Data from.txt Reading Data from.xls and.csv Reading Data from.mat User Interface

More information

Working with Excel Files. a = round(rand(5,3)*100) xlswrite('rand.xlsx',a) b = xlsread('rand.xlsx')

Working with Excel Files. a = round(rand(5,3)*100) xlswrite('rand.xlsx',a) b = xlsread('rand.xlsx') File I/O Working with Excel Files a = round(rand(5,3)*100) xlswrite('rand.xlsx',a) b = xlsread('rand.xlsx') Excel files with mixed content >> [nums, txt, raw] = xlsread('texttest.xls') nums = 123 333 432

More information

Low-Level File I/O. 1. Open a file. 2. Read or write data into the file. 3. Close the file. Zheng-Liang Lu 1 / 14

Low-Level File I/O. 1. Open a file. 2. Read or write data into the file. 3. Close the file. Zheng-Liang Lu 1 / 14 Low-Level File I/O Low-level file I/O functions allow the most control over reading or writing data to a file. However, these functions require that you specify more detailed information about your file

More information

13-Writing Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

13-Writing Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie 13-Writing Data text: Chapter 4.4-4.5 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie Overview Writing Data to.txt Writing Data to.xls and.csv Writing Data to.mat Dr. Henry Louie

More information

Beyond the Mouse A Short Course on Programming

Beyond the Mouse A Short Course on Programming 1 / 14 Beyond the Mouse A Short Course on Programming 5. Matlab IO: Getting data in and out of Matlab Ronni Grapenthin and Glenn Thompson Geophysical Institute, University of Alaska Fairbanks October 10,

More information

Scalars and Variables

Scalars and Variables Chapter 2 Scalars and Variables In this chapter, we will discuss arithmetic operations with scalars (numbers, really an array with only one element) and variables. Scalars can be used directly in calculations

More information

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006 STAT 39 Handout Making Plots with Matlab Mar 26, 26 c Marina Meilă & Lei Xu mmp@cs.washington.edu This is intended to help you mainly with the graphics in the homework. Matlab is a matrix oriented mathematics

More information

MATLAB. Data and File Management

MATLAB. Data and File Management MATLAB Data and File Management File Details Storage of data in variables and arrays is temporary. For permanent retention of data files are used. All of us are familiar with files. We save our work (e.g.

More information

Advanced C Programming Topics

Advanced C Programming Topics Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8

More information

PROGRAMMING WITH MATLAB WEEK 13

PROGRAMMING WITH MATLAB WEEK 13 PROGRAMMING WITH MATLAB WEEK 13 FILE INPUT AND OUTPUT Input statements read in values from the default or standard input device. In most systems the default input device is the keyboard. The input expression

More information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

Chapter 9. Above: An early computer input/output device on the IBM 7030 (STRETCH)

Chapter 9. Above: An early computer input/output device on the IBM 7030 (STRETCH) Chapter 9 Above: An early computer input/output device on the IBM 7030 (STRETCH) http://computer-history.info/page4.dir/pages/ibm.7030.stretch.dir/ Io One of the moon s of Jupiter (A Galilean satellite)

More information

Lecture 5: Strings, Printing, and File I/O

Lecture 5: Strings, Printing, and File I/O 1 Lecture 5: Strings, Printing, and File I/O 1 Learning objectives At the of this class you should be able to... be able to name the three Matlab data types most commonly used in ME 352 be able to use

More information

Unit 4. Input/Output Functions

Unit 4. Input/Output Functions Unit 4 Input/Output Functions Introduction to Input/Output Input refers to accepting data while output refers to presenting data. Normally the data is accepted from keyboard and is outputted onto the screen.

More information

AWK - PRETTY PRINTING

AWK - PRETTY PRINTING AWK - PRETTY PRINTING http://www.tutorialspoint.com/awk/awk_pretty_printing.htm Copyright tutorialspoint.com So far we have used AWK's print and printf functions to display data on standard output. But

More information

Matlab. Carlo Tomasi. Since images are matrices of numbers, many vision algorithms are naturally implemented

Matlab. Carlo Tomasi. Since images are matrices of numbers, many vision algorithms are naturally implemented Matlab Carlo Tomasi MATLAB is a simple and useful high-level language for matrix manipulation. It is often convenient to use MATLAB even for programs for which this language is not the ideal choice in

More information

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018)

Introduction to MATLAB Programming. Chapter 3. Linguaggio Programmazione Matlab-Simulink (2017/2018) Introduction to MATLAB Programming Chapter 3 Linguaggio Programmazione Matlab-Simulink (2017/2018) Algorithms An algorithm is the sequence of steps needed to solve a problem Top-down design approach to

More information

Quick MATLAB Syntax Guide

Quick MATLAB Syntax Guide Quick MATLAB Syntax Guide Some useful things, not everything if-statement Structure: if (a = = = ~=

More information

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs).

MATLAB INTRODUCTION. Matlab can be used interactively as a super hand calculator, or, more powerfully, run using scripts (i.e., programs). L A B 6 M A T L A B MATLAB INTRODUCTION Matlab is a commercial product that is used widely by students and faculty and researchers at UTEP. It provides a "high-level" programming environment for computing

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab 1 Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control Using of M-File Writing User

More information

An Introductory Tutorial on Matlab

An Introductory Tutorial on Matlab 1. Starting Matlab An Introductory Tutorial on Matlab We follow the default layout of Matlab. The Command Window is used to enter MATLAB functions at the command line prompt >>. The Command History Window

More information

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060 CS 2060 Files and Streams Files are used for long-term storage of data (on a hard drive rather than in memory). Files and Streams Files are used for long-term storage of data (on a hard drive rather than

More information

Using the fprintf command to save output to a file.

Using the fprintf command to save output to a file. Using the fprintf command to save output to a file. In addition to displaying output in the Command Window, the fprintf command can be used for writing the output to a file when it is necessary to save

More information

PART 2 DEVELOPING M-FILES

PART 2 DEVELOPING M-FILES PART 2 DEVELOPING M-FILES Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 17 September 2018 Topic Outcomes Week Topic Topic Outcomes 6-8 Creating

More information

CME 192: Introduction to Matlab

CME 192: Introduction to Matlab CME 192: Introduction to Matlab Matlab Basics Brett Naul January 15, 2015 Recap Using the command window interactively Variables: Assignment, Identifier rules, Workspace, command who and whos Setting the

More information

DATA STRUCTURES USING C

DATA STRUCTURES USING C DATA STRUCTURES USING C File Handling in C Goals By the end of this unit you should understand how to open a file to write to it. how to open a file to read from it. how to open a file to append data to

More information

Programming 1. Script files. help cd Example:

Programming 1. Script files. help cd Example: Programming Until now we worked with Matlab interactively, executing simple statements line by line, often reentering the same sequences of commands. Alternatively, we can store the Matlab input commands

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

Standard C Library Functions

Standard C Library Functions Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB

SECTION 2: PROGRAMMING WITH MATLAB. MAE 4020/5020 Numerical Methods with MATLAB SECTION 2: PROGRAMMING WITH MATLAB MAE 4020/5020 Numerical Methods with MATLAB 2 Functions and M Files M Files 3 Script file so called due to.m filename extension Contains a series of MATLAB commands The

More information

Organization of a file

Organization of a file File Handling 1 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example: Consider keeping students records 100 students

More information

Introduction to file management

Introduction to file management 1 Introduction to file management Some application require input to be taken from a file and output is required to be stored in a file. The C language provides the facility of file input-output operations.

More information

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

More information

Strings and I/O functions

Strings and I/O functions Davies: Computer Vision, 5 th edition, online materials Matlab Tutorial 2 1 Strings and I/O functions 1. Introduction It is the purpose of these online documents to provide information on Matlab and its

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CSci 4061 Introduction to Operating Systems. Input/Output: High-level

CSci 4061 Introduction to Operating Systems. Input/Output: High-level CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

QUIZ: What is the output of this MATLAB code? >> A = [2,4,10,13;16,3,7,18; 8,4,9,25;3,12,15,17]; >> length(a) >> size(a) >> B = A(2:3, 1:3) >> B(5)

QUIZ: What is the output of this MATLAB code? >> A = [2,4,10,13;16,3,7,18; 8,4,9,25;3,12,15,17]; >> length(a) >> size(a) >> B = A(2:3, 1:3) >> B(5) QUIZ: What is the output of this MATLAB code? >> A = [2,4,10,13;16,3,7,18; 8,4,9,25;3,12,15,17]; >> length(a) >> size(a) >> B = A(2:3, 1:3) >> B(5) QUIZ Ch.3 Introduction to MATLAB programming 3.1 Algorithms

More information

CSCE155N Matlab Examination 3 Solution. March 29, 2013

CSCE155N Matlab Examination 3 Solution. March 29, 2013 CSCE155N Matlab Examination 3 Solution March 29, 2013 Name: NUID: This examination consists of 4 questions and you have 50 minutes to complete the test. Show all steps (including any computations/explanations)

More information

Chapter 1 Introduction to MATLAB

Chapter 1 Introduction to MATLAB EGR115 Introduction to Computing for Engineers Introduction to MATLAB from: S.J. Chapman, MATLAB Programming for Engineers, 5 th Ed. 2016 Cengage Learning Topics Introduction: Computing for Engineers 1.1

More information

EE168 Lab/Homework #1 Introduction to Digital Image Processing Handout #3

EE168 Lab/Homework #1 Introduction to Digital Image Processing Handout #3 EE168 Lab/Homework #1 Introduction to Digital Image Processing Handout #3 We will be combining laboratory exercises with homework problems in the lab sessions for this course. In the scheduled lab times,

More information

Input/Output: Advanced Concepts

Input/Output: Advanced Concepts Input/Output: Advanced Concepts CSE 130: Introduction to Programming in C Stony Brook University Related reading: Kelley/Pohl 1.9, 11.1 11.7 Output Formatting Review Recall that printf() employs a control

More information

Files and File Management Scripts Logical Operations Conditional Statements

Files and File Management Scripts Logical Operations Conditional Statements Files and File Management Scripts Logical Operations Conditional Statements Files and File Management Matlab provides a group of commands to manage user files pwd: Print working directory displays the

More information

C Basics And Concepts Input And Output

C Basics And Concepts Input And Output C Basics And Concepts Input And Output Report Working group scientific computing Department of informatics Faculty of mathematics, informatics and natural sciences University of Hamburg Written by: Marcus

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #47 File Handling In this video, we will look at a few basic things about file handling in C. This is a vast

More information

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

More information

Writing to and reading from files

Writing to and reading from files Writing to and reading from files printf() and scanf() are actually short-hand versions of more comprehensive functions, fprintf() and fscanf(). The difference is that fprintf() includes a file pointer

More information

Eng Marine Production Management. Introduction to Matlab

Eng Marine Production Management. Introduction to Matlab Eng. 4061 Marine Production Management Introduction to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. Matlab is available

More information

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 printf and scanf Streams (input and output)

More information

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Goals of C  The Goals of C (cont.)  Goals of this Lecture The Design of C: A Rational Reconstruction Goals of this Lecture The Design of C: A Rational Reconstruction Help you learn about: The decisions that were available to the designers of C The decisions that were made by the designers of C Why? Learning

More information

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6 1. What is File management? In real life, we want to store data permanently so that later on we can retrieve it and reuse it. A file is a collection of bytes stored on a secondary storage device like hard

More information

ENG120. Misc. Topics

ENG120. Misc. Topics ENG120 Misc. Topics Topics Files in C Using Command-Line Arguments Typecasting Working with Multiple source files Conditional Operator 2 Files and Streams C views each file as a sequence of bytes File

More information

Matlab Input/Output. Goal of this section Learn user-controlled Input Output Read/write data files (optional) Input/output 5-

Matlab Input/Output. Goal of this section Learn user-controlled Input Output Read/write data files (optional) Input/output 5- Matlab Input/Output Goal of this section Learn user-controlled Input Output Read/write data files (optional) 85-232 Input/output 5-1 Input: initialization >> a=[-1 0 0 ; 1 1 0] >> b=[1, 2, 3; 2:4] >> b=[1,

More information

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL. Files Files enable permanent storage of information C performs all input and output, including disk files, by means of streams Stream oriented data files are divided into two categories Formatted data

More information

CSI 402 Lecture 2 Working with Files (Text and Binary)

CSI 402 Lecture 2 Working with Files (Text and Binary) CSI 402 Lecture 2 Working with Files (Text and Binary) 1 / 30 AQuickReviewofStandardI/O Recall that #include allows use of printf and scanf functions Example: int i; scanf("%d", &i); printf("value

More information

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 07: Data Input and Output Readings: Chapter 4 Input /Output Operations A program needs

More information

M.CS201 Programming language

M.CS201 Programming language Power Engineering School M.CS201 Programming language Lecture 16 Lecturer: Prof. Dr. T.Uranchimeg Agenda Opening a File Errors with open files Writing and Reading File Data Formatted File Input Direct

More information

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple Chapter 2 Interactive MATLAB use only good if problem is simple Often, many steps are needed We also want to be able to automate repeated tasks Automated data processing is common in Earth science! Automated

More information

Numerical Methods for Civil Engineers

Numerical Methods for Civil Engineers Numerical Methods for Civil Engineers Lecture 3 - MATLAB 3 Programming with MATLAB : - Script m-filesm - Function m-filesm - Input and Output - Flow Control Mongkol JIRAVACHARADET S U R A N A R E E UNIVERSITY

More information

An Introduction to MATLAB

An Introduction to MATLAB An Introduction to MATLAB Day 1 Simon Mitchell Simon.Mitchell@ucla.edu High level language Programing language and development environment Built-in development tools Numerical manipulation Plotting of

More information

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Chapter 3: Introduction to MATLAB Programming (4 th ed.) Chapter 3: Introduction to MATLAB Programming (4 th ed.) Algorithms MATLAB scripts Input / Output o disp versus fprintf Graphs Read and write variables (.mat files) User-defined Functions o Definition

More information

25.2 Opening and Closing a File

25.2 Opening and Closing a File Lecture 32 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 32: Dynamically Allocated Arrays 26-Nov-2018 Location: Chemistry 125 Time: 12:35 13:25 Instructor:

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12 BIL 104E Introduction to Scientific and Engineering Computing Lecture 12 Files v.s. Streams In C, a file can refer to a disk file, a terminal, a printer, or a tape drive. In other words, a file represents

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features

More information

Engineering program development 7. Edited by Péter Vass

Engineering program development 7. Edited by Péter Vass Engineering program development 7 Edited by Péter Vass Functions Function is a separate computational unit which has its own name (identifier). The objective of a function is solving a well-defined problem.

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 4 Input & Output Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline printf scanf putchar getchar getch getche Input and Output in

More information

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson)

Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion of this lesson) T-01-13-2009 GLY 6932/6862 Numerical Methods in Earth Sciences Spring 2009 Lesson 2 Characteristics of Good Code Writing (* acknowledgements to Dr. G. Spinelli, New Mexico Tech, for a substantial portion

More information

Lecture 9: File Processing. Quazi Rahman

Lecture 9: File Processing. Quazi Rahman 60-141 Lecture 9: File Processing Quazi Rahman 1 Outlines Files Data Hierarchy File Operations Types of File Accessing Files 2 FILES Storage of data in variables, arrays or in any other data structures,

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi CE 43 - Fall 97 Lecture 4 Input and Output Department of Computer Engineering Outline printf

More information

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming 1 Literal Constants Definition A literal or a literal constant is a value, such as a number, character or string, which may be assigned to a variable or a constant. It may also be used directly as a function

More information

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras Module No. #01 Lecture No. #1.1 Introduction to MATLAB programming

More information

Python Working with files. May 4, 2017

Python Working with files. May 4, 2017 Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output

More information

The Design of C: A Rational Reconstruction (cont.)

The Design of C: A Rational Reconstruction (cont.) The Design of C: A Rational Reconstruction (cont.) 1 Goals of this Lecture Recall from last lecture Help you learn about: The decisions that were available to the designers of C The decisions that were

More information

UNIX input and output

UNIX input and output UNIX input and output Disk files In UNIX a disk file is a finite sequence of bytes, usually stored on some nonvolatile medium. Disk files have names, which are called paths. We won t discuss file naming

More information

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed. Example 4 Printing and Plotting Matlab provides numerous print and plot options. This example illustrates the basics and provides enough detail that you can use it for typical classroom work and assignments.

More information

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 7 Input/Output

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 7 Input/Output ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 7 Input/Output Reading: Bowman, Chapters 10-12 READING FROM THE TERMINAL The READ procedure is used to read from the terminal. IDL

More information

1 Data Exploration: The 2016 Summer Olympics

1 Data Exploration: The 2016 Summer Olympics CS 1132 Fall 2016 Assignment 2 due 9/29 at 11:59 pm Adhere to the Code of Academic Integrity. You may discuss background issues and general strategies with others and seek help from course staff, but the

More information

C introduction: part 1

C introduction: part 1 What is C? C is a compiled language that gives the programmer maximum control and efficiency 1. 1 https://computer.howstuffworks.com/c1.htm 2 / 26 3 / 26 Outline Basic file structure Main function Compilation

More information

AROUND THE WORLD OF C

AROUND THE WORLD OF C CHAPTER AROUND THE WORLD OF C 1 1.1 WELCOME TO C LANGUAGE We want to make you reasonably comfortable with C language. Get ready for an exciting tour. The problem we would consider to introduce C language

More information

File (1A) Young Won Lim 11/25/16

File (1A) Young Won Lim 11/25/16 File (1A) Copyright (c) 2010-2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version

More information

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB? Appendix A Introduction to MATLAB A.1 What Is MATLAB? MATLAB is a technical computing environment developed by The Math- Works, Inc. for computation and data visualization. It is both an interactive system

More information