Using MATLAB (779505), страница 21
Текст из файла (страница 21)
This button also dismisses theImport Wizard. The Import Wizard displays a message in the MATLABcommand window, reporting that it created variables in the workspace. In thefollowing example, note how the numeric text data in each variable is importedas an array of doubles.Import Wizard created variables in the current workspace.>> whosNameSizeBytes Class6-8Importing Text DataAnnJohnMartinRob1x31x31x31x324242424doubledoubledoubledoublearrayarrayarrayarrayGrand total is 12 elements using 96 bytesUsing Import Functions with Text DataTo import text data from the command line or in an M-file, you must use one ofthe MATLAB import functions. Your choice of function depends on how thedata in the text file is formatted.The text data must be formatted in a uniform pattern of rows and columns,using a text character, called a delimiter or column separator, to separate eachdata item. The delimiter can be space, comma, semicolon, tab, or any othercharacter.
The individual data items can be alphabetic or numeric charactersor a mix of both.The text file may also contain one or more lines of text, called header lines, ormay use text headers to label each column or row. The following exampleillustrates a tab-delimited text file with header text and row and columnheaders.Text header lineColumn HeadersRow HeadersClass Grades for Spring TermGrade1 Grade2 Grade3John859095Ann909298Martin1009597Rob778693Tab-delimited dataTo find out how your data is formatted, view it in a text editor.
After youdetermine the format, scan the data format samples in Table 6-1 and look forthe sample that most closely resembles the format of your data. Read the topicreferred to in the table for more information.6-96Importing and Exporting DataTable 6-1: ASCII Data File Formats and MATLAB Import CommandsData Format SampleFileExtensionDescription1 2 3 4 56 7 8 9 10.txt.datSee “Importing Numeric Text Data” on page 6-11 formore information. You can also use the ImportWizard for this data format. See “Using the ImportWizard with Text Data” on page 6-4 for moreinformation.or other1;6;or1,6,2; 3; 4; 57; 8; 9; 10.txt.dat.csv2, 3, 4, 57, 8, 9, 10or otherAnn Type1 12.34 45 YesJoe Type2 45.67 67 No.txt.datSee “Importing Delimited ASCII Data Files” on page6-12 for more information. You can also use theImport Wizard for this data format.
See “Using theImport Wizard with Text Data” on page 6-4 for moreinformation.See “Importing Numeric Data with Text Headers”on page 6-13 for more information.or otherGrade1 Grade2 Grade391.589.277.388.067.891.067.378.192.5.txt.dator otherSee “Importing Numeric Data with Text Headers”on page 6-13 for more information. You can also usethe Import Wizard for this data format. See “Usingthe Import Wizard with Text Data” on page 6-4 formore information.If you are familiar with MATLAB import functions but not sure when to usethem, view Table 6-2 which compares the features of each function.6-10Importing Text DataTable 6-2: ASCII Data Import Function Feature ComparisonFunctionData TypeDelimitersNumber ofReturnValuesNotescsvreadNumeric dataOnlycommasOnePrimarily used withspreadsheet data.
Seealso the binary formatspreadsheet importfunctions.dlmreadNumeric dataAnycharacterOneFlexible and easy to use.fscanfAlphabetic andnumeric;however, bothtypes returnedin a singlereturn variableAnycharacterOnePart of low-level file I/Oroutines. Requires use offopen to obtain fileidentifier and fcloseafter read.loadNumeric dataOnly spacesOneEasy to use. Use thefunctional form of loadto specify the name ofthe output variable.textreadAlphabetic andnumericAnycharacterMultiplereturnvalues.Flexible, powerful, andeasy to use.
Use formatstring to specifyconversions.Importing Numeric Text DataIf your data file contains only numeric data, you can use many of the MATLABimport functions (listed in Table 6-2), depending on how the data is delimited.If the data is rectangular, that is, each row has the same number of elements,the simplest command to use is the load command.
(The load command canalso be used to import MAT-files, MATLAB’s binary format for saving theworkspace.)6-116Importing and Exporting DataFor example, the file named my_data.txt contains two rows of numbersdelimited by space characters.1 2 3 4 56 7 8 9 10When you use load as a command, it imports the data and creates a variablein the workspace with the same name as the filename, minus the file extension.load my_data.txt;whosNameSizemy_data2x5Bytes80Classdouble arraymy_datamy_data =12673849510If you want to name the workspace variable something other than the filename, use the functional form of load. In the following example, the data frommy_data.txt is loaded into the workspace variable A.A = load('my_data.txt');Importing Delimited ASCII Data FilesIf your data file uses a character other than a space as a delimiter, you have achoice of several import functions you can use.
(See Table 6-4 for a completelist.) The simplest to use is the dlmread function.For example, consider a file named ph.dat whose contents are separated bysemicolons.7.2;8.5;6.2;6.65.4;9.2;8.1;7.2To read the entire contents of this file into an array named A, enterA = dlmread('ph.dat', ';');6-12Importing Text DataYou specify the delimiter used in the data file as the second argument todlmread. Note that, even though the last items in each row are not followed bya delimiter, dlmread can still process the file correctly.
dlmread ignores spacecharacters between data elements. So, the preceding dlmread command workseven if the contents of ph.dat are7.2;5.4;8.5;9.26.2;6.6;8.1;7.2Importing Numeric Data with Text HeadersTo import an ASCII data file that contains text headers, use the textreadfunction, specifying the headerlines parameter. textread accepts a set ofpredefined parameters that control various aspects of the conversion. (For acomplete list of these parameters, see the textread reference page.) Theheaderlines parameter lets you specify the number of lines at the head of thefile that textread should ignore.For example, the file, grades.dat, contains formatted numeric data with aone-line text header.Grade1 Grade2 Grade378.855.945.999.566.878.089.577.056.7To import this data, use this command:[grade1 grade2 grade3] = textread('grades.dat','%f %f %f',...'headerlines',1)grade1 =78.800099.500089.5000grade2 =55.900066.800077.00006-136Importing and Exporting Datagrade3 =45.900078.000056.7000Importing Mixed Alphabetic and Numeric DataIf your data file contains a mix of alphabetic and numeric ASCII data, use thetextread function to import the data.
textread can return multiple outputvariables and you can specify the data type of each variable.For example, the file mydata.dat contains a mix of alphabetic and numericdata.SallyLarryTommyType1 12.34 45 YesType2 34.56 54 YesType1 67.89 23 NoNote To read an ASCII data file that contains primarily numeric data butwith text column headers, see “Importing Numeric Data with Text Headers”on page 6-13.To read the entire contents of the file mydata.dat into the workspace, specifythe name of the data file and the format string as arguments to textread.
Inthe format string, you include conversion specifiers that define how you wanteach data item to be interpreted. For example, specify %s for strings data, %ffor floating point data, and so on. (For a complete list of format specifiers, seethe textread reference page.)For each conversion specifier in your format string, you must specify a separateoutput variable. textread processes each data item in the file as specified inthe format string and puts the value in the output variable. The number ofoutput variables must match the number of conversion specifiers in the formatstring.In this example, textread reads the file mydata.dat, applying the formatstring to each line in the file until the end of the file.[names,types,x,y,answer] = textread('mydata.dat','%s %s %f ...%d %s',1)6-14Importing Text Datanames ='Sally''Larry''Tommy'types ='Type1''Type2''Type1'x =12.340034.560067.8900y =455423answer ='Yes''Yes''No'If your data uses a character other than a space as a delimiter, you must usethe textread parameter 'delimiter' to specify the delimiter.
For example, ifthe file mydata.dat used a semicolon as a delimiter, you would use thiscommand.[names,types,x,y,answer]=textread('mydata.dat','%s %s %f ...%d %s', 'delimiter',';')See the textread reference page for more information about these optionalparameters.6-156Importing and Exporting DataExporting ASCII DataMATLAB supports several ways to export data in many different ASCIIformats. For example, you may want to export a MATLAB matrix as text filewhere the rows and columns are represented as space-separated, numericvalues.This section describes how to use MATLAB functions to export data in severalcommon ASCII formats, including:• “Exporting Delimited ASCII Data Files” on page 6-17• “Using the diary Command to Export Data” on page 6-18The function you use depends on the amount of data you want to export and itsformat.If you are not sure which section describes your data, scan the data formatsamples in Table 6-3 and look for the sample that most nearly matches the dataformat you want to create.
















