Download presentation
Presentation is loading. Please wait.
Published byAmberlynn Walker Modified over 9 years ago
1
Nov. 28, 2005 Lecture 14 - By Paul Lin 1 CPET 190 Problem Solving with MATLAB Lecture 14 Professor Paul Lin http://www.etcs.ipfw.edu/~lin
2
Nov. 28, 2005 Lecture 14 - By Paul Lin 2 MATLAB Standard I/Os Standard I/Os Standard I/Os Standard input - keyboardStandard input - keyboard Standard output – monitor screenStandard output – monitor screen Standard error device – monitor screenStandard error device – monitor screen MATLAB I/Os MATLAB I/Os keyboard inputkeyboard input Filename = input(‘Enter a file name: ‘, ‘s’) Monitor outputMonitor output disp( ) function – display an array or text string fprintf( format,data) function – display data with desired format
3
Nov. 28, 2005 Lecture 14 - By Paul Lin 3 Lecture 14: File Input and Output MATLAB I/O Functions MATLAB I/O Functions diary( ) – save text of MATLAB sessiondiary( ) – save text of MATLAB session >> diary save( ) – save workspace variable to disksave( ) – save workspace variable to disk >> save FILENAME load( ) – load workspace variables from diskload( ) – load workspace variables from disk >> load FILENAME textread( ) – read formatted data from text filetextread( ) – read formatted data from text file
4
Nov. 28, 2005 Lecture 14 - By Paul Lin 4 Save and Load Function save function save function load function load function >> save 8_20_2004.mat >> clear >> whos >> load 8_20_2004.mat >> whos Name Size Bytes Class ans 1x1 8 double array x 1x1 8 double array y 1x1 8 double array Grand total is 3 elements using 24 bytes >> clear >> whos Current Directory
5
Nov. 28, 2005 Lecture 14 - By Paul Lin 5 MATLAB File Formats >>help filefomats Data formats Commands Returns MAT - MATLAB workspace load Variables in file. CSV - Comma separated numbers csvread Double array. DAT - Formatted text importdata Double array. DLM - Delimited text dlmread Double array. TAB - Tab separated textdlmreadDouble array. Spreadsheet formats Spreadsheet formats XLS - Excel worksheetxlsreadDouble array and cell array. WK1 - Lotus 123 worksheetwk1readDouble array and cell array. Scientific data formats Scientific data formats CDF - Common Data FormatcdfreadCell array of CDF records FITS - Flexible Image Transport System fitsreadPrimary or extension table data HDF - Hierarchical Data FormathdfreadHDF or HDF-EOS data set Movie formats Movie formats AVI - Movie avireadMATLAB movie.
6
Nov. 28, 2005 Lecture 14 - By Paul Lin 6 MATLAB File Formats >>help filefomats Data formats Command Returns Image formats TIFF - TIFF image imreadTruecolor, grayscale or indexed image(s). PNG - PNG imageimreadTruecolor, grayscale or indexed image. HDF - HDF imageimreadTruecolor or indexed image(s). BMP - BMP image imreadTruecolor or indexed image. JPEG - JPEG imageimreadTruecolor or grayscale image. GIF - GIF imageimreadIndexed image. PCX - PCX imageimreadIndexed image. XWD - XWD image imreadIndexed image. CUR - Cursor imageimreadIndexed image. ICO - Icon image imreadIndexed image. RAS - Sun raster image imreadTruecolor or indexed. PBM - PBM image imreadGrayscale image. PGM - PGM imageimreadGrayscale image. PPM - PPM imageimreadTruecolor image. Audio formats Audio formats AU - NeXT/Sun sound auread Sound data and sample rate. SND - NeXT/Sun sound auread Sound data and sample rate. WAV - Microsoft Wave sound wavread Sound data and sample rate
7
Nov. 28, 2005 Lecture 14 - By Paul Lin 7 MATLAB Low-Level File I/Os File Opening and Closing Functions File Opening and Closing Functions fopen( ) – open file for reading, writing, or appendingfopen( ) – open file for reading, writing, or appending fclose( ) – close file or filesfclose( ) – close file or files Binary I/O Binary I/O fread( ) – read binary data from filefread( ) – read binary data from file fwirte( ) – write binary data to filefwirte( ) – write binary data to file Formatted I/O Formatted I/O fscanf( ) – read formatted data from filefscanf( ) – read formatted data from file fprintf( ) – write formatted data to filefprintf( ) – write formatted data to file fgets( ) – read line from file, keep newline characterfgets( ) – read line from file, keep newline character fgetl( ) – read line form file, discard newline characterfgetl( ) – read line form file, discard newline character
8
Nov. 28, 2005 Lecture 14 - By Paul Lin 8 MATLAB Low-Level File I/Os (continued) String Conversion Functions String Conversion Functions sprinf( ) – write formatted data to stringsprinf( ) – write formatted data to string sscanf( ) – read string under format controlsscanf( ) – read string under format control File Positioning Functions File Positioning Functions ferros( ) – File I/O error statusferros( ) – File I/O error status feof( ) – test for end of filefeof( ) – test for end of file fseek( ) – set file position indicatorfseek( ) – set file position indicator ftell( ) – get file position indicatorftell( ) – get file position indicator frewind( ) – Rewind filefrewind( ) – Rewind file
9
Nov. 28, 2005 Lecture 14 - By Paul Lin 9 File Path Set File Path File -> Set Path -> Add Folder File -> Set Path -> Add Folder MTALAB Path Search -> G:\public_html\cpet190\ codes MTALAB Path Search -> G:\public_html\cpet190\ codes Click on Save button, and then Close button Click on Save button, and then Close button
10
Nov. 28, 2005 Lecture 14 - By Paul Lin 10 Example 14-1: Loading a Sequence of Data Files Create dataFiles Create dataFiles >> x = -10:0.1:10; >> y = 2*(x.^2) + 1; >> save dataFile1 >> clear y >> y = 2*(x.^2) + 10; >> save dataFile2 To open a sequence of enumerated data files To open a sequence of enumerated data files for file_no = 1: N fname = sprintf(‘testData%d’,file_no ); load(fname)end Create dataFiles Create dataFiles >> whos Name Size Bytes Class N 1x1 8 double array N 1x1 8 double array file_no 1x1 8 double array Fname 1x9 18 char array x 1x201 1608 double array y 1x201 1608 double array z 1x201 1608 double array >> plot(x, y) >> plot(x, z)
11
Nov. 28, 2005 Lecture 14 - By Paul Lin 11 File Processing Reading a file Open a file for reading Open a file for reading Process reading from the file Process reading from the file Close the file Close the file Appending to a file Open a file for appending Open a file for appending Process appending the file Process appending the file Close the file Close the file Writing to a file Open a file for writing Open a file for writing Process writing to the file Process writing to the file Close the file Close the file
12
Nov. 28, 2005 Lecture 14 - By Paul Lin 12 Typical File Processing Open files Open files fid = fopen(' file_name ', permissions), where permissions can be one of the following: fid = fopen(' file_name ', permissions), where permissions can be one of the following: 'r‘ - Open the file for reading. The file must exist. An error occurs if the file does not exist.'r‘ - Open the file for reading. The file must exist. An error occurs if the file does not exist. 'r+‘ - Open the file for reading and writing. The file mut exist. An error occure if the file does not exist'r+‘ - Open the file for reading and writing. The file mut exist. An error occure if the file does not exist 'w‘ - Open the file for writing, create if necessary'w‘ - Open the file for writing, create if necessary 'w+‘ - Truncate or create for read and write'w+‘ - Truncate or create for read and write 'a‘ - Append (create if necessary)'a‘ - Append (create if necessary) 'a+ ‘ – Read and append (create if necessary)'a+ ‘ – Read and append (create if necessary) Write to, Read from files Write to, Read from files Close files Close files
13
Nov. 28, 2005 Lecture 14 - By Paul Lin 13 Example 14-2: Create a file - a table of the exponential function Pseudo Code 1. Create x and y vectors for exponential function 2. Open A File for Writing 3. Write Formatted Data – fprinf(fid, ‘format specifiers’, data) 4. Close File The program %save_exp.m x = 0:.1:1; y = [x' exp(x)']; fid = fopen('expfucntion.txt','w'); fprintf(fid,'%f %f\n', y); fclose(fid); File Content: 0 1.0000 0.1000 1.1052 0.2000 1.2214 0.3000 1.3499 0.4000 1.4918 0.5000 1.6487 0.6000 1.8221 0.7000 2.0138 0.8000 2.2255 0.9000 2.4596 1.0000 2.7183
14
Nov. 28, 2005 Lecture 14 - By Paul Lin 14 Example 14-2: Create a file - a table of the exponential function We edit the program as shown in previous slide Set default directory or folder for storing the file Debug or test the program through the MATLAB M-file editor Open Windows Explorer and examine the created file
15
Nov. 28, 2005 Lecture 14 - By Paul Lin 15 Example 14-2: Create a file - a table of the exponential function Open the expfunction.txt file using Microsoft Wordpad Open the expfunction.txt file using Notepad
16
Nov. 28, 2005 Lecture 14 - By Paul Lin 16 Example 14-3: Reading Exponential Function File for Plotting %load_exp.m fid = fopen('expfucntion.txt','r'); % Retrieve data table a 11-by-2 [y1 count] = fscanf(fid,'%f', [11 2]); fclose(fid); % Extract first column x = y1(:,1) % Extract 2nd column exp_x = y1(:,2) plot(x, exp_x); grid on
17
Nov. 28, 2005 Lecture 14 - By Paul Lin 17 Example 14-4: Writing and Reading Binary Data %binary_file.m filename = input('Enter a file name: ', 's'); out_data = 100*rand(10, 1); [fid msg] = fopen(filename,'w'); % File open OK? if fid > 0 count = fwrite(fid, out_data, 'double'); count = fwrite(fid, out_data, 'double'); disp([int2str(count) ' value written to disk..']); disp([int2str(count) ' value written to disk..']); status = fclose(fid); status = fclose(fid);else % Failed to open the file % Failed to open the file disp(msg); disp(msg);end % Open the file for reading [fid msg] = fopen(filename, 'r'); if fid > 0 [in_data, count] = fread(fid, 10, 'double'); [in_data, count] = fread(fid, 10, 'double'); disp([int2str(count) ' value read from the disk..']); disp([int2str(count) ' value read from the disk..']); status = fclose(fid); status = fclose(fid);else % Failed to open the file % Failed to open the file disp(msg); disp(msg);endin_dataout_data
18
Nov. 28, 2005 Lecture 14 - By Paul Lin 18 Example 14-4: Writing and Reading Binary Data %binary_file.m filename = input('Enter a file name: ', 's'); out_data = 100*rand(10, 1); [fid msg] = fopen(filename,'w'); % File open OK? if fid > 0 count = fwrite(fid, out_data, 'double'); count = fwrite(fid, out_data, 'double'); disp([int2str(count) ' value written to disk..']); disp([int2str(count) ' value written to disk..']); status = fclose(fid); status = fclose(fid);else % Failed to open the file % Failed to open the file disp(msg); disp(msg);end % Open the file for reading [fid msg] = fopen(filename, 'r'); if fid > 0 [in_data, count] = fread(fid, 10, 'double'); [in_data, count] = fread(fid, 10, 'double'); disp([int2str(count) ' value read from the disk..']); disp([int2str(count) ' value read from the disk..']); status = fclose(fid); status = fclose(fid);else % Failed to open the file % Failed to open the file disp(msg); disp(msg);endin_dataout_data
19
Nov. 28, 2005 Lecture 14 - By Paul Lin 19 Example 14-4: Writing and Reading Binary Data in_data = 95.0129 95.0129 23.1139 23.1139 60.6843 60.6843 48.5982 48.5982 89.1299 89.1299 76.2097 76.2097 45.6468 45.6468 1.8504 1.8504 82.1407 82.1407 44.4703 44.4703 out_data = 95.0129 95.0129 23.1139 23.1139 60.6843 60.6843 48.5982 48.5982 89.1299 89.1299 76.2097 76.2097 45.6468 45.6468 1.8504 1.8504 82.1407 82.1407 44.4703 44.4703 Binary Files - Not Readable
20
Nov. 28, 2005 Lecture 14 - By Paul Lin 20 Summary MATLAB Standard I/Os - File Input and Output Save and Load Function MATLAB File Formats MATLAB Low-Level File I/Os File Path File Processing Examples Formatted Files Binary Files Be sure to read Chapter 8 of the Text book, MATLAB help
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.