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

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

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

Note that once a structurearray contains more than a single element, MATLAB does not displayindividual field contents when you type the array name. Instead, it shows asummary of the kind of information the structure contains.20-520Structures and Cell Arrayspatientpatient =1x2 struct array with fields:namebillingtestYou can also use the fieldnames function to obtain this information.fieldnames returns a cell array of strings containing field names.As you expand the structure, MATLAB fills in unspecified fields with emptymatrices so that:• All structures in the array have the same number of fields.• All fields have the same field names.For example, entering patient(3).name = 'Alan Johnson' expands thepatient array to size [1 3]. Now both patient(3).billing andpatient(3).test contain empty matrices.Note Field sizes do not have to conform for every element in an array.

In thepatient example, the name fields can have different lengths, the test fieldscan be arrays of different sizes, and so on.Building Structure Arrays Using the struct FunctionYou can preallocate an array of structures with the struct function. Its basicform isstr_array = struct('field1',val1,'field2',val2, ...)where the arguments are field names and their corresponding values. A fieldvalue can be a single value, represented by any MATLAB data construct, or acell array of values. All field values in the argument list must be of the samescale (single value or cell array).You can use different methods for preallocating structure arrays. Thesemethods differ in the way in which the structure fields are initialized. As an20-6Structuresexample, consider the allocation of a 1-by-3 structure array, weather, with thestructure fields temp and rainfall.

Three different methods for allocating suchan array are shown in this table.MethodSyntaxInitializationstructweather(3) =struct('temp',72,'rainfall',0.0);weather(3) is initialized with thefield values shown. The fields forthe other structures in the array,weather(1) and weather(2), areinitialized to the empty matrix.struct withrepmatweather =repmat(struct('temp',72,'rainfall',0.0),1,3);All structures in the weather arrayare initialized using one set of fieldvalues.struct withcell arraysyntaxweather = struct('temp',{68,80,72},'rainfall',{0.2,0.4,0.0});The structures in the weather arrayare initialized with distinct fieldvalues specified with cell arrays.Accessing Data in Structure ArraysUsing structure array indexing, you can access the value of any field or fieldelement in a structure array. Likewise, you can assign a value to any field orfield element.

For the examples in this section, consider this structure array.patientarraypatient(1)patient(2).name'John Doe'.billing127.00.test7918022075178210.namepatient(3)'Ann Lane'.billing 28.5073177.5205.test681181727011817068119169.name'Al Smith'.billing504.70.test80153181801531908015418220-720Structures and Cell ArraysYou can access subarrays by appending standard subscripts to a structurearray name. For example, the line below results in a 1-by-2 structure array.mypatients = patient(1:2)1x2 struct array with fields:namebillingtestThe first structure in the mypatients array is the same as the first structurein the patient array.mypatients(1)ans =name: 'John Doe'billing: 127test: [3x3 double]To access a field of a particular structure, include a period (.) after the structurename followed by the field name.str = patient(2).namestr =Ann LaneTo access elements within fields, append the appropriate indexing mechanismto the field name.

That is, if the field contains an array, use array subscripting;if the field contains a cell array, use cell array subscripting, and so on.test2b = patient(3).test(2,2)test2b =153Use the same notations to assign values to structure fields, for example,patient(3).test(2,2) = 7;20-8StructuresYou can extract field values for multiple structures at a time. For example, theline below creates a 1-by-3 vector containing all of the billing fields.bills = [patient.billing]bills =127.000028.5000504.7000Similarly, you can create a cell array containing the test data for the first twostructures.tests = {patient(1:2).test}tests =[3x3 double][3x3 double]Accessing Field Values Using setfield and getfieldDirect indexing is usually the most efficient way to assign or retrieve fieldvalues.

If, however, you only know the field name as a string – for example, ifyou have used the fieldnames function to obtain the field name within anM-file – you can use the setfield and getfield functions to do the same thing.getfield obtains a value or values from a field or field elementf = getfield(array,{array_index},'field',{field_index})where the field_index is optional, and array_index is optional for a 1-by-1structure array. The function syntax corresponds tof = array(array_index).field(field_index);For example, to access the name field in the second structure of the patientarray, use:str = getfield(patient,{2},'name');Similarly, setfield lets you assign values to fields using the syntaxf = setfield(array,{array_index},'field',{field_index},value)20-920Structures and Cell ArraysFinding the size of Structure ArraysUse the size function to obtain the size of a structure array, or of any structurefield.

Given a structure array name as an argument, size returns a vector ofarray dimensions. Given an argument in the form array(n).field, the sizefunction returns a vector containing the size of the field contents.For example, for the 1-by-3 structure array patient, size(patient) returnsthe vector [1 3]. The statement size(patient(1,2).name) returns the lengthof the name string for element (1,2) of patient.Adding Fields to StructuresYou can add a field to every structure in an array by adding the field to a singlestructure.

For example, to add a social security number field to the patientarray, use an assignment likepatient(2).ssn = '000–00–0000';Now patient(2).ssn has the assigned value. Every other structure in thearray also has the ssn field, but these fields contain the empty matrix until youexplicitly assign a value to them.Deleting Fields from StructuresYou can remove a given field from every structure within a structure arrayusing the rmfield function. Its most basic form isstruc2 = rmfield(array,'field')where array is a structure array and 'field' is the name of a field to removefrom it.

To remove the name field from the patient array, for example, enter:patient = rmfield(patient,'name');Applying Functions and OperatorsOperate on fields and field elements the same way you operate on any otherMATLAB array. Use indexing to access the data on which to operate. Forexample, this statement finds the mean across the rows of the test array inpatient(2).mean((patient(2).test)');20-10StructuresThere are sometimes multiple ways to apply functions or operators acrossfields in a structure array.

One way to add all the billing fields in the patientarray istotal = 0;for k = 1:length(patient)total = total + patient(k).billing;endTo simplify operations like this, MATLAB enables you to operate on alllike-named fields in a structure array. Simply enclose the array.fieldexpression in square brackets within the function call. For example, you cansum all the billing fields in the patient array usingtotal = sum ([patient.billing]);This is equivalent to using the comma-separated list.total = sum ([patient(1).billing, patient(2).billing...]);This syntax is most useful in cases where the operand field is a scalar field.Writing Functions to Operate on StructuresYou can write functions that work on structures with specific fieldarchitectures. Such functions can access structure fields and elements forprocessing.Note When writing M-file functions to operate on structures, you mustperform your own error checking.

That is, you must ensure that the codechecks for the expected fields.As an example, consider a collection of data that describes measurements, atdifferent times, of the levels of various toxins in a water source. The dataconsists of fifteen separate observations, where each observation containsthree separate measurements.You can organize this data into an array of 15 structures, where each structurehas three fields, one for each of the three measurements taken.20-1120Structures and Cell ArraysThe function concen, shown below, operates on an array of structures withspecific characteristics.

Its arguments must contain the fields lead, mercury,and chromium.function [r1,r2] = concen(toxtest);% Create two vectors. r1 contains the ratio of mercury to lead% at each observation. r2 contains the ratio of lead to chromium.r1 = [toxtest.mercury]./[toxtest.lead];r2 = [toxtest.lead]./[toxtest.chromium];% Plot the concentrations of lead, mercury, and chromium% on the same plot, using different colors for each.lead = [toxtest.lead];mercury = [toxtest.mercury];chromium = [toxtest.chromium];plot(lead,'r'); hold onplot(mercury,'b')plot(chromium,'y'); hold offTry this function with a sample structure array like test.test(1).lead = .007; test(2).lead = .031; test(3).lead = .019;test(1).mercury = .0021; test(2).mercury = .0009;test(3).mercury = .0013;test(1).chromium = .025; test(2).chromium = .017;test(3).chromium = .10;Organizing Data in Structure ArraysThe key to organizing structure arrays is to decide how you want to accesssubsets of the information.

This, in turn, determines how you build the arraythat holds the structures, and how you break up the structure fields.20-12StructuresFor example, consider a 128-by-128 RGB image stored in three separatearrays; RED, GREEN, and BLUE.Blue intensityvaluesGreen intensityvaluesRed intensityvalues0.1120.7651.0000.4550.0211.0001.0000.9900.9020.986 0.2340.128 0.8630.985 0.7610.783 0.2240.500 0.3111.000 0.8670.945 0.9980.941 1.0000.867 0.834..0.342 0.647 0.5150.111 0.300 0.2050.523 0.428 0.7120.214 0.604 0.9180.100 0.121 0.1130.288 0.187 0.2040.208...0.576 0.7600.4320.109...0.995 0.9970.5210.426...0.727 0.9950.698.0.395 ....0.123 ...0.051 ....0.893 ...0.876 ...0.798 ...0.689 0.706 0.1180.535 0.532 0.6530.314 0.265 0.1590.553 0.633 0.5280.441 0.465 0.5120.398 0.401 0.4210.320...0.988 0.9120.8160.119...0.182 0.2190.5260.125...0.495 0.1280.929.0.344 ....0.126 ....0.175 ...0.531 ...0.910 ...0.726 ...0.8840.9250.1010.4930.5120.3980.7130.3280.133............................20-1320Structures and Cell ArraysThere are at least two ways you can organize such data into a structure array.Plane organizationElement-by-element organizationAB.r.g0.112 0.986 0.234 0.432 ...0.765 0.128 0.863 0.521 ...1.000 0.985 0.761 0.698 ......B(1,1)0.342 0.647 0.515 0.816 ...0.111 0.300 0.205 0.526 ...0.523 0.428 0.712 0.929 ......B(1,2).r.r0.2340.342.g0.647.g0.5150.689.b0.706.b0.118.r.g.bB(2,1).b0.689 0.706 0.118 0.884 ...0.535 0.532 0.653 0.925 ...0.314 0.265 0.159 0.101 ......1-by-1 structure array where each field is a 128-by-128 array.

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

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

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

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