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

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

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

HDF uses zero-based indexingso the first attribute has the index value zero, the second has an index valueone, and so on.This code example returns the contents of the first attribute associated with adata set identified by sds_id. In this case, the value of the attribute is the6-38Working with HDF Datacharacter string 'my local attribute'. MATLAB automatically sizes thereturn value, ds_attr, to fit the value of the attribute.attr_idx = 0;[ds_attr, status] = hdfsd('readattr', sds_id, attr_idx)ds_attr =my local attributestat =0Reading Data from an HDF FileAfter you open an HDF file and select a data set in the file, you can read theentire data set, or part of the data set.

In the HDF SD API, you use theSDreaddata routine to read a data set. In MATLAB, use the hdfsd function,specifying readdata as the first argument. As other arguments, specify:• The HDF SD data set identifier (sds_id) returned by SDselect• The location in the data set where you want to start reading data, specifiedas a vector of index values, called the start vector in HDF terminology• The number of elements along each dimension to skip between each readoperation, specified as a vector scalar values, called the stride vector in HDFterminology• The total number of elements to read along each dimension, specified as avector of scalar values, called the edges vector in HDF terminologyFor example, to read the entire contents of a data set containing this 3-by-5matrix of numeric values1 2 3 4 56 7 8 9 1011 12 13 14 15you could use this code.[ds_name, ds_ndims, ds_dims, ds_type, ds_atts, stat] =hdfsd('getinfo',sds_id);ds_start = zeros(1,ds_ndims); % Creates the vector [0 0]ds_stride = [];6-396Importing and Exporting Datads_edges = ds_dims;[ds_data, status] =hdfsd('readdata',sds_id,ds_start,ds_stride,ds_edges);disp(ds_data)123678111213491451015In this example, note the following:• The return values of SDgetinfo are used to specify the dimensions of thereturn values and as arguments to SDreaddata.• To read from the beginning of a data set, specify zero for each element of thestart vector (ds_start).

Note how the example uses SDgetinfo to determinethe length of the start vector.• To read every element of a data set, specify one for each element of the stridevector or specify an empty array ([]).• To read every element of a data set, set each element of the edges vector tothe size of each dimension of the data set.Note Use the dimensions vector returned by SDgetinfo, dsdims, to set thevalue of the edges vector because SDgetinfo returns these values inrow-major order, the ordering used by HDF.

MATLAB stores data incolumn-major order. An array referred to as a 3-by-5 array in MATLAB isdescribed as a 5-by-3 array in HDF.Reading a Portion of a Data SetTo read less than the entire data set, use the start, stride, and edges vectors tospecify where you want to start reading data and how much data you want toread.For example, this code fragment uses SDreaddata to read the entire second rowof the sample data set.6-40Working with HDF Data1 2 3 4 56 7 8 9 1011 12 13 14 15Note that in the start, stride, and edges arguments, you must specify thedimensions in column-major order, that is, [columns,rows]. In addition, notethat you must use zero-based indexing in these arguments.ds_start = [0 1] % Start reading at the first column, second rowds_stride = []; % Read each elementds_edges = [5 1]; % Read a 1-by-5 vector of data[ds_data, status] =hdfsd('readdata',sds_id,ds_start,ds_stride,ds_edges);disp(ds_data)678910For more information about specifying ranges in data sets, see “WritingMATLAB Data to an HDF File” on page 6-44.Closing HDF Files and HDF Data setsAfter reading data from a data set in an HDF file, you must close access to thedata set and the file.

The HDF SD API includes functions to perform thesetasks. See “Closing HDF Data Sets” on page 6-46 for more information.Exporting MATLAB Data in an HDF FileTo export data from MATLAB in an HDF file, you must use the functions in theHDF API associated with the 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 write data to 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.6-416Importing and Exporting DataThe HDF SD Export Programming ModelThe programming model for exporting HDF SD data involves these steps:1 Create the HDF file, or open an existing one.2 Create a data set in the file, or select an existing one.3 Write data to the data set.4 Close access to the data set and the HDF file.You can optionally include information in the HDF file that describes yourdata.

See “Including Metadata in an HDF File” on page 6-47 for moreinformation.Creating an HDF FileTo export MATLAB data in HDF format, you must first create an HDF file, oropen an existing one. In the HDF SD API, you use the SDstart routine. InMATLAB, use the hdfsd function, specifying start as the first argument. Asother arguments, specify:• A text string specifying the name you want to assign to the HDF file (or thename of an existing HDF file)• A text string specifying the HDF SD interface file access modeFor example, this code creates an HDF file named mydata.hdf.sd_id = hdfsd('start','mydata.hdf','DFACC_CREATE');If it can create (or open) the file, SDstart returns an HDF SD file identifier,named sd_id in the example.

Otherwise, it returns -1.When you specify the DFACC_CREATE access mode, SDstart creates the file andinitializes the HDF SD multifile interface. If you specify DFACC_CREATE modeand the file already exists, SDstart fails, returning -1. To open an existingHDF file, you must use HDF read or write modes. For information about usingSDstart in these modes, see “Opening HDF Files” on page 6-34.6-42Working with HDF DataCreating an HDF Data SetAfter creating the HDF file, or opening an existing one, you must create a dataset in the file for each MATLAB array you want to export. In the HDF SD API,you use the SDcreate routine to create data sets. In MATLAB, you use thehdfsd function, specifying create as the first argument.

To write data to anexisting data set, you must obtain the HDF SD data set identifier. See“Selecting Data Sets in HDF Files” on page 6-36 for more information.This table lists the other arguments to SDcreate.ArgumentMATLAB Data TypeValid HDF SD file identifierReturned from SDstartName you want assigned to thedata setText stringData type of the data setText string. For information aboutspecifying data types, see “ImportingHDF Data into the MATLABWorkspace” on page 6-33Number of dimensions in thedata set. This is called the rank ofthe data set in HDF terminologyScalar numeric valueSize of each dimensionVectorThe values you assign to these arguments depend on the MATLAB array youwant to export. For example, to export this MATLAB 3-by-5 array of doubles,A = [ 1 2 3 4 5 ; 6 7 8 9 10 ; 11 12 13 14 15 ];you could set the values of these arguments as in this code fragment.ds_nameds_typeds_rankds_dims===='A';'double';ndims(A);fliplr(size(A));sds_id = hdfsd('create',sd_id,ds_name,ds_type,ds_rank,ds_dims);6-436Importing and Exporting DataIf SDcreate can successfully create the data set, it returns an HDF SD data setidentifier (sds_id).

Otherwise, SDcreate returns -1.Note In this example, note how the code fragment reverses the order of thevalues in the dimensions argument (ds_dims). This processing is necessarybecause the MATLAB size function returns the dimensions in column-majororder and HDF expects to receive dimensions in row-major order.Once you create a data set, you cannot change its characteristics. You can,however, modify the data it contains. To do this, initiate access to the data set,using SDselect, and write to the data set as described in “Writing MATLABData to an HDF File” on page 6-44.Writing MATLAB Data to an HDF FileAfter creating an HDF file and creating a data set in the file, you can write datato the entire data set or just a portion of the data set. In the HDF SD API, youuse the SDwritedata routine.

In MATLAB, use the hdfsd function, specifyingwritedata as the first argument.This table lists the other arguments to SDwritedata.6-44ArgumentMATLAB Data TypeValid data set identifier (sds_id)Returned by SDcreateLocation in the data set where you want tostart writing data, called the start vector inHDF terminologyVector of index valuesNumber of elements along each dimension toskip between each write operation, called thestride vector in HDF terminologyVector of scalar valuesTotal number of elements to write along eachdimension, called the edges vector in HDFterminologyVector of scalar valuesMATLAB array to be writtenArray of doublesWorking with HDF DataNote You must specify the values of the start, stride, and edges arguments inrow-major order, rather than the column-major order used in MATLAB.

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

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

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

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