Using MATLAB (779505), страница 26
Текст из файла (страница 26)
Notehow the example uses fliplr to reverse the order of the dimensions in thevector returned by the size function before assigning it as the value of theedges argument.The values you assign to these arguments depend on the MATLAB array youwant to export. For example, this code fragment writes this MATLAB 3-by-5array of doubles,A = [ 1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15 ];into an HDF file.ds_start = zeros(1:ndims(A)); % Start at the beginningds_stride = [];% Write every element.ds_edges = fliplr(size(A));% Reverse the dimensions.stat = hdfsd('writedata',sds_id,ds_start, ds_stride, ds_edges, A)If it can write the data to the data set, SDwritedata returns 0; otherwise, itreturns -1.Note SDwritedata queues write operations.
To ensure that these queuedwrite operations are executed, you must close the file, using the SDend routine.See “Closing an HDF File” on page 6-46 for more information. As aconvenience, MATLAB provides a function, MLcloseall, that you can use toclose all open data sets and file identifiers with a single call. See “Using theMATLAB HDF Utility API” on page 6-49 for more information.Writing Data to Portions of Data SetsTo write less than the entire data set, use the start, stride, and edges vectorsto specify where you want to start writing data and how much data you wantto write.6-456Importing and Exporting DataFor example, this code fragment uses SDwritedata to replace the values of theentire second row of the sample data set1 2 3 4 56 7 8 9 1011 12 13 14 15with the vector, B.B = [ 9 9 9 9 9]In the example, the start vector specifies that you want to start the writeoperation in the first column of the second row.
Note how HDF uses zero-basedindexing and specifies the column dimension first. In MATLAB, you wouldspecify this location as (2,1). The edges argument specifies the dimensions ofthe data to be written. Note that the size of the array of data to be written mustmatch the edge specification.ds_start = [0 1] % Start writing at the first column, second row.ds_stride = []; % Write every element.ds_edges = [5 1]; % Each row is a 1-by-5 vector.stat = hdfsd('writedata',sds_id,ds_start,ds_stride,ds_edges,B);Closing HDF Data SetsAfter writing data to a data set in an HDF file, you must close access to the dataset.
In the HDF SD API, you use the SDendaccess routine to close a data set.In MATLAB, use the hdfsd function, specifying endaccess as the firstargument. As the only other argument, specify a valid HDF SD data setidentifier, sds_id in this example.stat = hdfsd('endaccess',sds_id);Closing an HDF FileAfter writing data to a data set and closing the data set, you must also close theHDF file.
In the HDF SD API, you use the SDend routine. In MATLAB, use thehdfsd function, specifying end as the first argument. As the only otherargument, specify a valid HDF SD file identifier, sd_id in this example.stat = hdfsd('end',sd_id);You must close access to all the data sets in an HDF file before closing it.6-46Working with HDF DataNote Closing an HDF file executes all the write operations that have beenqueued using SDwritedata. As a convenience, the MATLAB HDF Utility APIprovides a function, MLcloseall, that can close all open data set and fileidentifiers with a single call.
See “Using the MATLAB HDF Utility API” onpage 6-49 for more information.Including Metadata in an HDF FileYou can optionally include information in an HDF file that describes your data.HDF defines an separate annotation API, however, the HDF SD API includesan annotation capability.
This section only describes the annotationcapabilities of the HDF SD API. For information about the Annotation API, seethe official NCSA documentation.Types of AttributesUsing HDF SD API, you can associate attributes with three types of HDFobjects:• An entire HDF file – File attributes, also called global attributes, generallycontain information pertinent to all the data sets in the file.• A data set in and HDF file – Data set attributes, also called local attributes,describe individual data sets.• A dimension of a data set – Dimension attributes provide informationapplicable to an individual data set dimension.Multiple AttributesYou can associate multiple attributes with a single HDF object.
HDFmaintains an attribute index for each object. The attribute index is zero-based.The first value has the index value zero, the second has the value one, and soon. You access an attribute by its index value.Each attribute has the format name=value, where name (called label in HDFterminology) is a text string up to 256 characters in length and value containsone or more entries of the same data type. A single attribute can have multiplevalues.6-476Importing and Exporting DataAssociating Attributes with HDF SD ObjectsIn the HDF SD API, you use the SDsetattr routine to associate an attributewith a file, data set or dimension.
In MATLAB, use the hdfsd function,specifying setattr as the first argument. As other arguments, specify• A valid HDF SD identifier associated with the object. This value could be afile identifier (sd_id), a data set identifier (sds_id), or a dimension identifier(dim_id).• A text string that defines the name of the attribute. The SD interfacesupports predefined attributes that have reserved names and, in some cases,data types. For information about these attributes, see “Creating PredefinedAttributes” on page 6-48.• The attribute valueFor example, this code creates a global attribute, named my_global_attr, andassociates it with the HDF file identified by sd_id.status = hdfsd('setattr',sd_id,'my_global_attr','my_attr_val');Note In the NCSA documentation, the SDsetattr routine has two additionalarguments: data type and the number of values in the attribute.
When callingthis routine from MATLAB, you do not have to include these arguments. TheMATLAB HDF function can determine the data type and size of the attributefrom the value you specify.Creating Predefined AttributesPredefined attributes are identical to user-defined attributes except that thethe HDF SD API has already defined their names and data types.
For example,the HDF SD API defines an attribute, named cordsys, in which you can specifythe coordinate system used by the data set. Possible values of this attributeinclude the text strings 'cartesian', 'polar', and 'spherical'.Predefined attributes can be useful because they establish conventions thatapplications can depend on. The HDF SD API supports predefined attributesfor data sets and dimensions only; there are no predefined attributes for files.For a complete list of the predefined attributes, see the NCSA documentation.6-48Working with HDF DataIn the HDF SD API, you create predefined attributes the same way you createuser-defined attributes, using the SDsetattr routine.
In MATLAB, use thehdfsd function, specifying setattr as the first argument.attr_name = 'cordsys';attr_value = 'polar';status = hdfsd('setattr',sds_id,attr_name,attr_value);The HDF SD API also includes specialized functions for writing and readingthe predefined attributes. These specialized functions, such as SDsetdatastrs,are sometimes easier to use, especially when reading or writing multiplerelated predefined attributes. You must use specialized functions to read orwrite the predefined dimension attributes.Using the MATLAB HDF Utility APIIn addition to the standard HDF APIs, listed in Table , , on page 6-30,MATLAB supports an API of utility functions that are designed to make usingHDF in the MATLAB environment easier.For example, the MATLAB utility API includes a function, MLlistinfo, whichyou can use to view all types of open HDF identifiers, such as HDF SD fileidentifiers. MATLAB updates these lists whenever HDF identifiers are createdor closed.This code obtains a list of all open HDF file and data set identifiers, using theMLlistinfo function.
In this example, only two identifiers are open.hdfml('listinfo')No open RI identifiersNo open GR identifiersNo open grid identifiersNo open grid file identifiersNo open annotation identifiersNo open AN identifiersOpen scientific dataset identifiers:262144Open scientific data file identifiers:393216No open Vdata identifiersNo open Vgroup identifiers6-496Importing and Exporting DataNoNoNoNoNoNoNoopenopenopenopenopenopenopenVfile identifierspoint identifierspoint file identifiersswath identifiersswath file identifiersaccess identifiersfile identifiersClosing All Open HDF IdentifiersTo close all open HDF identifiers in a single call, use the MLcloseall function.This call closes all open HDF identifiers.hdfml('closeall')6-50Using Low-Level File I/O FunctionsUsing Low-Level File I/O FunctionsMATLAB includes a set of low-level file I/O functions that are based on the I/Ofunctions of the ANSI Standard C Library.
If you know C, therefore, you areprobably familiar with these routines.For example, the MATLAB file I/O functions use the same programming modelas the C language routines. To read or write data, you perform these steps:1 Open the file, using fopen. fopen returns a file identifier which you use withall the other low-level file I/O routines.2 Operate on the file.a Read binary data using fread.b Write binary data using fwrite.cRead text strings from a file line-by-line using fgets/fgetl.d Read formatted ASCII data using fscanf.eWrite formatted ASCII data using fprintf.3 Close the file, using fclose.This section also describes how these functions affect the current position inthe file where read or write operations happen and how you can change theposition in the file.Note While the MATLAB file I/O commands are modeled on the C languageI/O routines, in some ways their behavior is different. For example, the freadfunction is “vectorized,” that is, it continues reading until it encounters a textstring or the end of file.
These sections, and the MATLAB reference pages forthese functions, highlight any differences in behavior.6-516Importing and Exporting DataOpening FilesBefore reading or writing a text or binary file, you must open it with the fopencommand.fid = fopen('filename','permission')Specifying the Permissions StringThe permission string specifies the kind of access to the file you require.Possible permission strings include:• r for reading only• w for writing only• a for appending only• r+ for both reading and writingNote Systems such as Microsoft Windows that distinguish between text andbinary files may require additional characters in the permission string, suchas 'rb' to open a binary file for reading.Using the Returned File Identifier (fid)If successful, fopen returns a a nonnegative integer, called a file identifier(fid).















