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

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

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

Cell 2 contains a structure with three vector fields.20-3120Structures and Cell ArraysWhen building cell arrays of structures, you must use content indexing.Similarly, you must use content indexing to obtain the contents of structureswithin cells. The syntax for content indexing is:cell_array{index}.fieldFor example, to access the label field of the structure in cell 1, usec_str{1}.label.20-3221Function HandlesBenefits of Using Function Handles .

. . . . . . . . 21-3A Simple Function Handle . . . . . . . . . . . . . . . 21-5Constructing a Function Handle . . . . . . . . . . . 21-7Maximum Length of a Function Name . . . . . . . . . . 21-7Evaluating a Function Through Its Handle .

. . . . . 21-9Function Evaluation and Overloading . . . . . . . . . . 21-9Examples of Function Handle Evaluation . . . . . . . . 21-10Displaying Function Handle Information . . . . . . 21-13Fields Returned by the Functions Command . . . . . . 21-14Types of Function Handles . . .

. . . . . . . . . . . 21-17Function Handle Operations . . . . . . .Converting Function Handles to Function NamesConverting Function Names to Function HandlesTesting for Data Type . . . . . . . . . . . .Testing for Equality . . . . . . . . . . . .....................21-2121-2121-2221-2321-23Saving and Loading Function Handles . . . . . . . 21-25Handling Error Conditions . .

. . . . . . .Handles to Nonexistent Functions . . . . . . . .Including Path In the Function Handle ConstructorEvaluating a Nonscalar Function Handle . . . . .............21-2621-2621-2621-27Historical Note - Evaluating Function Names . . . . 21-2821Function HandlesA function handle is a MATLAB data type that contains information used inreferencing a function. When you create a function handle, MATLAB stores inthe handle all the information about the function that it needs to execute, orevaluate, it later on. Typically, a function handle is passed in an argument listto other functions.

It is then used in conjunction with feval to evaluate thefunction to which the handle belongs.A MATLAB function handle is more than just a reference to a function. It oftenrepresents a collection of function methods, overloaded to handle differentargument types. When you create a handle to a function, MATLAB takes asnapshot of all built-in and M-file methods of that name that are on theMATLAB path and in scope at that time, and stores access information for allof those methods in the handle.When you evaluate a function handle, MATLAB considers only those functionsthat were stored within the handle when it was created. Other functions thatmight now be on the path or in scope are not considered.

It is the combinationof which function methods are mapped to by the handle and what argumentsthe handle is evaluated with that determines which is the actual function thatMATLAB dispatches to.This chapter addresses the following topics:• “Benefits of Using Function Handles”• “Constructing a Function Handle”• “Evaluating a Function Through Its Handle”• “Displaying Function Handle Information”• “Function Handle Operations”• “Saving and Loading Function Handles”• “Handling Error Conditions”• “Historical Note - Evaluating Function Names”21-2Benefits of Using Function HandlesBenefits of Using Function HandlesFunction handles enable you to do all of the following:• Pass function access information to other functions• Capture all methods of an overloaded function• Allow wider access to subfunctions and private functions• Ensure reliability when evaluating functions• Reduce the number of files that define your functions• Improve performance in repeated operations• Manipulate handles in arrays, structures, and cell arraysThis section also includes an example of using a simple function handle.

See “ASimple Function Handle” on page 21-5.Pass Function Access Information to Other FunctionsYou can pass a function handle as an argument in a call to another function.The handle contains access information that enables the receiving function tocall the function for which the handle was constructed.You can evaluate a function handle from within another function even if thehandle’s function is not in the scope of the evaluating function. This is becausethe function performing the evaluation has all the information it needs withinthe function handle.For the same reason, you can also evaluate a function handle even when thehandle’s function is no longer on the MATLAB search path.You must use the MATLAB feval command to evaluate the function in afunction handle.

When you pass a function handle as an argument into anotherfunction, then the function receiving the handle uses feval to evaluate thefunction handle.Capture All Methods of An Overloaded FunctionBecause many MATLAB functions are overloaded, a function handle oftenmaps to a number of code sources (e.g., built-in code, M-files), that implementthe function. A function handle stores the access to all of the overloadedsources, or methods, that are on the MATLAB path at the time the handle iscreated.21-321Function HandlesWhen you evaluate an overloaded function handle, MATLAB follows the usualrules of selecting which method to evaluate, basing the selection on theargument types passed in the function call.

See “How MATLAB DeterminesWhich Method to Call” on page 22-67, for more information on how MATLABselects overloaded functions.For example, there are three built-in functions and one M-file function thatdefine the abs function on the standard MATLAB path. A function handlecreated for the abs function contains access information on all four of thesefunction sources.

If you evaluate the function with an argument of the doubletype, then the built-in function that takes a double argument is executed.Allow Wider Access to Subfunctions and Private FunctionsBy definition, all MATLAB functions have a certain scope. They are visible toother MATLAB entities within that scope, but not visible outside of it. You caninvoke a function directly from another function that is within its scope, but notfrom a function outside that scope.Subfunctions and private functions are, by design, limited in their visibility toother MATLAB functions.

You can invoke a subfunction only by anotherfunction that is defined within the same M-file. You can invoke a privatefunction only from a function in the directory immediately above the \privatesubdirectory.When you create a handle to a function that has limited scope, the functionhandle stores all the information MATLAB needs to evaluate the function fromany location in the MATLAB environment.

If you create a handle to asubfunction while the subfunction is in scope, (that is, you create it from withinthe M-file that defines the subfunction), you can then pass the handle to codethat resides outside of that M-file and evaluate the subfunction from beyond itsusual scope. The similar case holds true for private functions.Ensure Reliability When Evaluating FunctionsFunction handles allow you more control over what methods get executed whena function is evaluated. If you create a function handle for a function withoverloaded methods, making sure that only the intended methods are withinscope when the handle is created gives you control over which methods areexecuted when MATLAB evaluates the handle.

This can isolate you frommethods that might be in scope at the time of evaluation that you didn’t knowabout.21-4Benefits of Using Function HandlesReduce the Number of Files That Define Your FunctionsYou can use function handles to help reduce the number of M-files required todefine your functions. The problem with grouping a number of functions in oneM-file is that this defines them as subfunctions, and thus reduces their scopein MATLAB.

Using function handles to access these subfunctions removes thislimitation. This enables you to group functions as you want and reduce thenumber of files you have to manage.Improve Performance in Repeated OperationsMATLAB performs a lookup on a function at the time you create a functionhandle and then stores this access information in the handle itself. Oncedefined, you can use this handle in repeated evaluations without incurring theperformance delay associated with function lookup each time.Manipulate Handles in Arrays, Structures, and Cell ArraysAs a standard MATLAB data type, a function handle can be manipulated andoperated on in the same manner as other MATLAB data types. You can createarrays, structures, or cell arrays of function handles.

Access individualfunction handles within these data structures in the same way that you accesselements of a numeric array or structure.Create n-dimensional arrays of handles using either of the concatenationmethods used to form other types of MATLAB arrays, [] or cat. All operationsinvolving matrix manipulation are supported for function handles.A Simple Function HandleThe repmat function is an elementary matrix function, which is defined inMATLAB with the single M-file, repmat.m. If you create a function handle tothe repmat function, MATLAB stores in the handle the information it will needlater to evaluate the function.

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

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

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

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