Using MATLAB (779505), страница 24

Файл №779505 Using MATLAB (Using MATLAB) 24 страницаUsing MATLAB (779505) страница 242017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 24)

For example, in C syntax,the SDfileinfo routine returns data about an HDF file in two outputarguments, ndatasets and nglobal_atts.status = SDfileinfo(sd_id, ndatasets, nglobal_atts);To call this routine from MATLAB, change the output arguments into returnvalues.[ndatasets, nglobal_atts, status] = hdfsd('fileinfo',sd_id);Specify the return values in the same order as they appear as outputarguments.

The function status return value is always specified last.Handling HDF Library Symbolic ConstantsThe C versions of the HDF APIs use symbolic constants, defined in header files,to specify modes and data types. For example, the SDstart routine uses asymbolic constant to specify the mode in which to open an HDF file.sd_id = SDstart("my_file.hdf",DFACC_RDONLY);When calling this routine from MATLAB, specify these constants as textstrings.sd_id = hdfsd('start','my_file.hdf','DFACC_RDONLY')6-32Working with HDF DataIn MATLAB, you can specify the entire constant or leave off the prefix.

Forexample, in this call to SDstart, you can use any of these variations as theconstant text string: 'DFACC_RDONLY', 'dfacc_rdonly', or 'rdonly'. Note thatyou can use any combination of upper- and lower-case characters.Importing HDF Data into the MATLAB WorkspaceTo import HDF data into MATLAB, you must use the routines in the HDF APIassociated with the particular HDF data type. Each API has a particularprogramming model, that is, a prescribed way to use the routines to open theHDF file, access data sets in the file, and read data from the data sets. (In HDFterminology, the numeric arrays stored in HDF files are called data sets.)To illustrate this concept, this section details the programming model of oneparticular HDF API: the Scientific Data (SD) API.

For information aboutworking with other HDF APIs, see the official NCSA documentation.Note The following sections, when referring to specific routines in the HDFSD API, use the C library name rather than the MATLAB function name. TheMATLAB syntax is used in all examples.The HDF SD Import Programming ModelTo import data in HDF SD format, you must use API routines to perform thesesteps:1 Open the file containing HDF SD data sets.2 Select the data set in the file that you want to import.3 Read the data from the data set.4 Close access to the data set and HDF file.There are several additional steps that you may also need to perform, such asretrieving information about the contents of the HDF file or the data sets in thefile.

The following sections provide more detail about the basic steps as well asoptional steps.6-336Importing and Exporting DataOpening HDF FilesTo import an HDF SD data set, you must first open the file containing the dataset. In the HDF SD API, you use the SDstart routine to open the file andinitialize the HDF interface.

In MATLAB, you use the hdfsd function withstart specified as the first argument.SDstart accepts these arguments:• A text string specifying the name of the file you want to open• A text string specifying the mode in which you want to open itFor example, this code opens the file mydata.hdf for read access.sd_id = hdfsd('start','mydata.hdf','read');If SDstart can find and open the file specified, it returns an HDF SD fileidentifier, named sd_id in the example. Otherwise, it returns -1.The HDF SD API supports several file access modes. You use a symbolicconstant, defined by the HDF SD API, to specify each mode.

In MATLAB, youspecify these constants as text strings. You can specify the full HDF constantor one of the abbreviated forms listed in table.HDF File Creation ModeHDF Symbolic ConstantMATLAB StringCreate a new file'DFACC_CREATE''create'Read access'DFACC_RDONLY''read' or'rdonly'Read and write access'DFACC_RDWR''rdwr' or'write'Retrieving Information About an HDF FileAfter opening a file, you can get information about what the file contains usingthe SDfileinfo routine. In MATLAB, you use the hdfsd function withfileinfo specified as the first argument. This function returns the number ofdata sets in the file and whether the file includes any global attributes.

(Formore information about global attributes, see “Retrieving Attributes from anHDF File” on page 6-35.)6-34Working with HDF DataAs an argument, SDfileinfo accepts the SD file identifier, sd_id, returned bySDstart. In this example, the HDF file contains three data sets and one globalattribute.[ndatasets, nglobal_atts, stat] = hdfsd('fileinfo',sd_id)ndatasets =3nglobal_atts =1status =0Retrieving Attributes from an HDF FileHDF files are self-documenting, that is, they can optionally includeinformation, called attributes, that describes the data the file contains.Attributes associated with an HDF file are called global attributes.

(You canalso associate attributes with data sets or dimensions. For more informationabout these attributes, see “Including Metadata in an HDF File” on page 6-47.)In the HDF SD API, you use the SDreadattr routine to retrieve globalattributes from an HDF file. In MATLAB, you use the hdfsd function,specifying readattr as the first argument. As other arguments, you specify:• The HDF SD file identifier (sd_id) returned by the SDstart routine• The index value specifying the attribute you want to view.

HDF useszero-based indexing so the first global attribute has an index value zero, thesecond has an index value one, and so on.For example, this code returns the contents of the first global attribute, whichis simply the character string 'my global attribute'.attr_idx = 0;[attr, status] = hdfsd('readattr', sd_id, attr_idx)attr =my global attributestat =06-356Importing and Exporting DataMATLAB automatically sizes the return value, attr, to fit the data in theattribute.Retrieving Attributes by Name. Attributes have names as well as values. If youknow the name of an attribute, you can use the SDfindattr function todetermine its index value so you can retrieve it.

In MATLAB, you use the hdfsdfunction, specifying findattr as the first argument.As other arguments, you specify:• The HDF SD file identifier, when searching for global attributes• A text string specifying the name of the attributeSDfindattr searches all the global attributes associated with the file. If it findsan attribute with this name, SDfindattr returns the index of the attribute. Youcan then use this index value to retrieve the attribute using SDreadattr.This example uses SDfindattr to obtain the index for the attribute namedmy_att and then passes this index as an argument to SDreadattr.attr_idx = hdfsd('findattr',sd_id,'my_att');[attr, status] = hdfsd('readattr', sd_id, attr_idx);Selecting Data Sets in HDF FilesAfter opening an HDF file, you must specify the data set in the file that youwant to read.

An HDF file can contain multiple data sets. In the HDF SD API,you use the SDselect routine to select a data set. In MATLAB, you use thehdfsd function, specifying select as the first argument.As arguments, this function accepts:• The HDF SD file identifier (sd_id) returned by SDstart• The index value specifying the attribute you want to view. HDF useszero-based indexing so the first global attribute has an index value zero, thesecond has an index value one, and so on.For example, this code selects the third data set in the HDF file identified bysd_id.

If SDselect finds the specified data set in the file, it returns an HDF SDdata set identifier, called sds_id in the example. If it cannot find the data set,it returns -1.6-36Working with HDF DataNote Do not confuse HDF SD file identifiers, named sd_id in the examples,with HDF SD data set identifiers, named sds_id in the examples.sds_idx = 2; % HDF uses zero-based indexing.sds_id = hdfsd('select',sd_id,sds_idx)Retrieving Data Sets by NameData sets in HDF files can be named.

If you know the name of the data set youare interested in, but not its index value, you can determine its index by usingthe SDnametoindex routine. In MATLAB, use the hdfsd function, specifyingnametoindex as the first argument.Getting Information About a Data SetAfter you select a data set in an HDF file, you can obtain information about thedata set, such as the number and size of the array dimensions. You need thisinformation to read the data set using the SDreaddata function. (See “ReadingData from an HDF File” on page 6-39 for more information.)In the HDF SD API, you use the SDgetinfo routine to gather this information.In MATLAB, use the hdfsd function, specifying getinfo as the first argument.In addition, you must specify the HDF SD data set identifier returned bySDselect (sds_id).This table lists the information returned by SDgetinfo.Data Set Information ReturnedMATLAB Data TypeNameCharacter arrayNumber of dimensionsScalarSize of each dimensionVectorData type of the data stored inthe arrayCharacter arrayNumber of attributes associatedwith the data setScalar6-376Importing and Exporting DataFor example, this code retrieves information about the data set identified bysds_id.[dsname, dsndims, dsdims, dstype, dsatts, stat] =hdfsd('getinfo',sds_id)dsname =Adsndims =2dsdims =53dstype =doubledsatts =0stat =0Retrieving Data Set AttributesLike HDF files, HDF SD data sets are self-documenting, that is, they canoptionally include information, called attributes, that describes the data in thedata set.

Attributes associated with a data set are called local attributes. (Youcan also associate attributes with files or dimensions. For more informationabout these attributes, see “Including Metadata in an HDF File” on page 6-47.)In the HDF SD API, you use the SDreadattr routine to retrieve localattributes. In MATLAB, use the hdfsd function, specifying readattr as thefirst argument. As other arguments, specify• The HDF SD data set identifier (sds_id) returned by SDselect• The index of the attribute you want to view.

Характеристики

Тип файла
PDF-файл
Размер
6,57 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
7021
Авторов
на СтудИзбе
261
Средний доход
с одного платного файла
Обучение Подробнее