Nov. 28, 2005 Lecture 14 - By Paul Lin 1 CPET 190 Problem Solving with MATLAB Lecture 14 Professor...

20
Nov. 28, 2005 Nov. 28, 2005 Lecture 14 - By Paul Lin Lecture 14 - By Paul Lin 1 CPET 190 CPET 190 Problem Solving with Problem Solving with MATLAB MATLAB Lecture 14 Lecture 14 Professor Paul Lin Professor Paul Lin http://www.etcs.ipfw.edu/ http://www.etcs.ipfw.edu/ ~lin ~lin

Transcript of Nov. 28, 2005 Lecture 14 - By Paul Lin 1 CPET 190 Problem Solving with MATLAB Lecture 14 Professor...

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 11

CPET 190 CPET 190

Problem Solving with Problem Solving with MATLAB MATLAB

Lecture 14Lecture 14

Professor Paul LinProfessor Paul Lin

http://www.etcs.ipfw.edu/~linhttp://www.etcs.ipfw.edu/~lin

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 22

MATLAB Standard I/Os MATLAB Standard I/Os

Standard I/OsStandard 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/OsMATLAB I/Os• keyboard inputkeyboard input

Filename = input(‘Enter a file name: ‘, ‘s’)Filename = input(‘Enter a file name: ‘, ‘s’)• Monitor outputMonitor output

disp( ) function – display an array or text stringdisp( ) function – display an array or text string

fprintf( format,data) function – display data with fprintf( format,data) function – display data with desired format desired format

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 33

Lecture 14: File Input and OutputLecture 14: File Input and Output

MATLAB I/O FunctionsMATLAB I/O Functions• diary( ) – save text of MATLAB sessiondiary( ) – save text of MATLAB session

>>>> diary diary• save( ) – save workspace variable to disksave( ) – save workspace variable to disk

>> >> save FILENAMEsave FILENAME• load( ) – load workspace variables from load( ) – load workspace variables from

diskdisk

>> >> load FILENAMEload FILENAME• textread( ) – read formatted data from text textread( ) – read formatted data from text

filefile

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 44

Save and Load FunctionSave and Load Function

save functionsave function load functionload function

>> save 8_20_2004.mat>> clear>> whos>> load 8_20_2004.mat>> whosName 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

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 55

MATLAB File FormatsMATLAB File Formats

>>help filefomats>>help filefomatsData formats Data formats Commands Commands ReturnsReturns

MAT - MATLAB workspace MAT - MATLAB workspace load load Variables in file.Variables in file.CSV - Comma separated numbers CSV - Comma separated numbers csvread csvread Double array.Double array.DAT - Formatted text DAT - Formatted text importdata importdata Double array.Double array.DLM - Delimited text DLM - Delimited text dlmread dlmread Double array.Double array.TAB - Tab separated textTAB - Tab separated text dlmreaddlmread Double array.Double array. Spreadsheet formatsSpreadsheet formatsXLS - Excel worksheetXLS - Excel worksheet xlsreadxlsread Double array and cell array.Double array and cell array.WK1 - Lotus 123 worksheetWK1 - Lotus 123 worksheet wk1readwk1read Double array and cell array.Double array and cell array. Scientific data formatsScientific data formatsCDF - Common Data FormatCDF - Common Data Format cdfreadcdfread Cell array of CDF recordsCell array of CDF recordsFITS - Flexible Image Transport System FITS - Flexible Image Transport System fitsreadfitsread Primary or extension table Primary or extension table

datadataHDF - Hierarchical Data FormatHDF - Hierarchical Data Format hdfreadhdfread HDF or HDF-EOS data setHDF or HDF-EOS data set

Movie formatsMovie formatsAVI - Movie AVI - Movie avireadaviread MATLAB movie.MATLAB movie.

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 66

MATLAB File FormatsMATLAB File Formats>>help filefomats>>help filefomats

Data formats Data formats Command Command ReturnsReturnsImage formatsImage formats

TIFF - TIFF image TIFF - TIFF image imreadimread Truecolor, grayscale or indexed Truecolor, grayscale or indexed image(s).image(s).

PNG - PNG imagePNG - PNG image imreadimread Truecolor, grayscale or indexed image.Truecolor, grayscale or indexed image.HDF - HDF imageHDF - HDF image imreadimread Truecolor or indexed image(s).Truecolor or indexed image(s).BMP - BMP image BMP - BMP image imreadimread Truecolor or indexed image.Truecolor or indexed image.JPEG - JPEG imageJPEG - JPEG image imreadimread Truecolor or grayscale image.Truecolor or grayscale image.GIF - GIF imageGIF - GIF image imreadimread Indexed image.Indexed image.PCX - PCX imagePCX - PCX image imreadimread Indexed image.Indexed image.XWD - XWD image XWD - XWD image imreadimread Indexed image.Indexed image.CUR - Cursor imageCUR - Cursor image imreadimread Indexed image.Indexed image.ICO - Icon image ICO - Icon image imreadimread Indexed image.Indexed image.RAS - Sun raster image RAS - Sun raster image imreadimread Truecolor or indexed.Truecolor or indexed.PBM - PBM image PBM - PBM image imreadimread Grayscale image.Grayscale image.PGM - PGM imagePGM - PGM image imreadimread Grayscale image.Grayscale image.PPM - PPM imagePPM - PPM image imreadimread Truecolor image.Truecolor image. Audio formatsAudio formatsAU - NeXT/Sun sound AU - NeXT/Sun sound auread Sound data and sample rate.auread Sound data and sample rate.SND - NeXT/Sun sound SND - NeXT/Sun sound auread Sound data and sample rate.auread Sound data and sample rate.WAV - Microsoft Wave sound wavread Sound data and sample rateWAV - Microsoft Wave sound wavread Sound data and sample rate

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 77

MATLAB Low-Level File I/OsMATLAB Low-Level File I/Os

File Opening and Closing File Opening and Closing FunctionsFunctions• fopen( ) – open file for fopen( ) – open file for

reading, writing, or reading, writing, or appendingappending

• fclose( ) – close file or filesfclose( ) – close file or files Binary I/OBinary I/O

• fread( ) – read binary data fread( ) – read binary data from filefrom file

• fwirte( ) – write binary data fwirte( ) – write binary data to file to file

Formatted I/OFormatted I/O• fscanf( ) – read formatted fscanf( ) – read formatted

data from filedata from file• fprintf( ) – write formatted fprintf( ) – write formatted

data to filedata to file• fgets( ) – read line from file, fgets( ) – read line from file,

keep newline character keep newline character • fgetl( ) – read line form file, fgetl( ) – read line form file,

discard newline characterdiscard newline character

Disk Storage

Create/Save/

Retrieve

Data Files

Text File

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 88

MATLAB Low-Level File I/Os MATLAB Low-Level File I/Os (continued)(continued)

String Conversion FunctionsString 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 FunctionsFile Positioning Functions• ferros( ) – File I/O error status ferros( ) – 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

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 99

File PathFile Path

Set File PathSet File Path File -> Set Path -> Add File -> Set Path -> Add

FolderFolder MTALAB Path Search -> MTALAB Path Search ->

G:\public_html\cpet190\G:\public_html\cpet190\codescodes

Click on Save button, Click on Save button, and then Close buttonand then Close button

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1010

Example 14-1: Loading a Sequence Example 14-1: Loading a Sequence of Data Filesof Data Files

Create dataFilesCreate dataFiles>> x = -10:0.1:10;>> x = -10:0.1:10;

>> y = 2*(x.^2) + 1;>> y = 2*(x.^2) + 1;

>> save dataFile1>> save dataFile1

>> clear y >> clear y

>> y = 2*(x.^2) + 10;>> y = 2*(x.^2) + 10;

>> save dataFile2>> save dataFile2

To open a sequence of To open a sequence of enumerated data files enumerated data files for file_no = 1: Nfor file_no = 1: N

fname = fname = sprintf(‘testDatasprintf(‘testData%d’,file_no);%d’,file_no);

load(fname)load(fname)

endend

Create dataFilesCreate dataFiles

>> whos>> whosName Size Name Size Bytes Class Bytes Class

NN 1x1 1x1 8 double array 8 double array

file_nofile_no 1x1 1x1 8 double array 8 double array

FnameFname 1x9 1x9 18 char array 18 char array

x 1x201 1608 double arrayx 1x201 1608 double array

y 1x201 1608 double arrayy 1x201 1608 double array

z 1x201 1608 double arrayz 1x201 1608 double array

>> plot(x , y)>> plot(x , y)

>> plot(x, z)>> plot(x, z)

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1111

File ProcessingFile Processing

Reading a fileReading a file Open a file for readingOpen a file for reading Process reading from the fileProcess reading from the file Close the fileClose the file

Appending to a fileAppending to a file Open a file for appendingOpen a file for appending Process appending the fileProcess appending the file Close the fileClose the file

Writing to a fileWriting to a file Open a file for writingOpen a file for writing Process writing to the fileProcess writing to the file Close the fileClose the file

Disk Storage

Create/Save/

Retrieve

Data Files

Text File

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1212

Typical File ProcessingTypical File Processing

Open filesOpen files fid = fopen(fid = fopen('' file_name file_name '', permissions), where , permissions), where

permissions can be one of the following: permissions can be one of the following: • 'r‘ - Open the file for reading. The file must exist. 'r‘ - Open the file for reading. The file must exist.

An error occurs if the file does not exist.An error occurs if the file does not exist.• 'r+‘ - Open the file for reading and writing. The file 'r+‘ - Open the file for reading and writing. The file

mut exist. An error occure if the file does not exist 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 filesWrite to, Read from files Close filesClose files

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1313

Example 14-2: Create a file - a table of Example 14-2: Create a file - a table of the exponential functionthe exponential function

Pseudo CodePseudo Code1. Create x and y vectors for 1. Create x and y vectors for

exponential functionexponential function2. Open A File for Writing 2. Open A File for Writing 3. Write Formatted Data – fprinf(fid, 3. Write Formatted Data – fprinf(fid,

‘format specifiers’, data)‘format specifiers’, data)4. Close File4. Close File

The programThe program%save_exp.m%save_exp.mx = 0:.1:1; y = [x' exp(x)'];x = 0:.1:1; y = [x' exp(x)'];fid = fopen('expfucntion.txt','w');fid = fopen('expfucntion.txt','w');fprintf(fid,'%f %f\n', y);fprintf(fid,'%f %f\n', y);fclose(fid);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

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1414

Example 14-2: Create a file - a table of Example 14-2: Create a file - a table of the exponential functionthe exponential function

We edit the program We edit the program as shown in previous as shown in previous slideslide

Set default directory Set default directory or folder for storing or folder for storing the filethe file

Debug or test the Debug or test the program through the program through the MATLAB M-file editorMATLAB M-file editor

Open Windows Open Windows Explorer and examine Explorer and examine the created file the created file

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1515

Example 14-2: Create a file - a Example 14-2: Create a file - a table of the exponential functiontable of the exponential function

Open the Open the expfunction.txt file expfunction.txt file using Microsoft using Microsoft WordpadWordpad

Open the Open the expfunction.txt file expfunction.txt file using Notepad using Notepad

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1616

Example 14-3: Reading Exponential Example 14-3: Reading Exponential Function File for PlottingFunction File for Plotting

%load_exp.m%load_exp.mfid = fid =

fopen('expfucntion.txt','r');fopen('expfucntion.txt','r');% Retrieve data table a 11-by-2% Retrieve data table a 11-by-2[y1 count] = fscanf(fid,'%f', [11 [y1 count] = fscanf(fid,'%f', [11

2]);2]);fclose(fid);fclose(fid);% Extract first column% Extract first columnx = y1(:,1)x = y1(:,1)% Extract 2nd column% Extract 2nd columnexp_x = y1(:,2)exp_x = y1(:,2)plot(x, exp_x); grid onplot(x, exp_x); grid on

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 11

1.2

1.4

1.6

1.8

2

2.2

2.4

2.6

2.8

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1717

Example 14-4: Writing and Example 14-4: Writing and Reading Binary DataReading Binary Data

%binary_file.m%binary_file.m

filename = input('Enter a file name: ', 's');filename = input('Enter a file name: ', 's');

out_data = 100*rand(10, 1);out_data = 100*rand(10, 1);

[fid msg] = fopen(filename,'w');[fid msg] = fopen(filename,'w');

% File open OK?% File open OK?

if fid > 0if fid > 0

count = fwrite(fid, out_data, 'double');count = fwrite(fid, out_data, 'double');

disp([int2str(count) ' value written to disp([int2str(count) ' value written to disk ..']);disk ..']);

status = fclose(fid);status = fclose(fid);

elseelse

% Failed to open the file% Failed to open the file

disp(msg);disp(msg);

endend

% Open the file for reading% Open the file for reading[fid msg] = fopen(filename, 'r');[fid msg] = fopen(filename, 'r');if fid > 0if fid > 0 [in_data, count] = fread(fid, 10, [in_data, count] = fread(fid, 10, 'double');'double'); disp([int2str(count) ' value read disp([int2str(count) ' value read from the disk ..']);from the disk ..']); status = fclose(fid);status = fclose(fid);elseelse % Failed to open the file% Failed to open the file disp(msg);disp(msg);endendin_datain_dataout_dataout_data

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1818

Example 14-4: Writing and Example 14-4: Writing and Reading Binary DataReading Binary Data

%binary_file.m%binary_file.m

filename = input('Enter a file name: ', 's');filename = input('Enter a file name: ', 's');

out_data = 100*rand(10, 1);out_data = 100*rand(10, 1);

[fid msg] = fopen(filename,'w');[fid msg] = fopen(filename,'w');

% File open OK?% File open OK?

if fid > 0if fid > 0

count = fwrite(fid, out_data, 'double');count = fwrite(fid, out_data, 'double');

disp([int2str(count) ' value written to disp([int2str(count) ' value written to disk ..']);disk ..']);

status = fclose(fid);status = fclose(fid);

elseelse

% Failed to open the file% Failed to open the file

disp(msg);disp(msg);

endend

% Open the file for reading% Open the file for reading[fid msg] = fopen(filename, 'r');[fid msg] = fopen(filename, 'r');if fid > 0if fid > 0 [in_data, count] = fread(fid, 10, [in_data, count] = fread(fid, 10, 'double');'double'); disp([int2str(count) ' value read disp([int2str(count) ' value read from the disk ..']);from the disk ..']); status = fclose(fid);status = fclose(fid);elseelse % Failed to open the file% Failed to open the file disp(msg);disp(msg);endendin_datain_dataout_dataout_data

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 1919

Example 14-4: Writing and Reading Example 14-4: Writing and Reading Binary DataBinary Data

in_data =in_data =

95.012995.0129 23.113923.1139 60.684360.6843 48.598248.5982 89.129989.1299 76.209776.2097 45.646845.6468 1.85041.8504 82.140782.1407 44.470344.4703

out_data =out_data =

95.012995.0129 23.113923.1139 60.684360.6843 48.598248.5982 89.129989.1299 76.209776.2097 45.646845.6468 1.85041.8504 82.140782.1407 44.470344.4703

Binary Files - Not Readable

Nov. 28, 2005Nov. 28, 2005 Lecture 14 - By Paul LinLecture 14 - By Paul Lin 2020

SummarySummary

MATLAB Standard I/Os - File Input and Output MATLAB Standard I/Os - File Input and Output Save and Load Function Save and Load Function MATLAB File FormatsMATLAB File Formats MATLAB Low-Level File I/OsMATLAB Low-Level File I/Os File PathFile Path File Processing ExamplesFile Processing Examples Formatted FilesFormatted Files Binary FilesBinary Files

Be sure to read Chapter 8 of the Text book, Be sure to read Chapter 8 of the Text book, MATLAB helpMATLAB help