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

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

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

This isshown in f.methods.cell.f = functions(@deblank)f =function: 'deblank'type: 'overloaded'file: 'matlabroot\toolbox\matlab\strfun\deblank.m'21-1521Function Handlesmethods: [1x1 struct]f.methodsans =cell: 'matlabroot\toolbox\matlab\strfun\@cell\deblank.m'If you evaluate the @deblank function handle with a cell argument, MATLABcalls the deblank method in the @cell directory. But, for any other argumenttypes, MATLAB calls the default M-file shown in the file field.Function MethodsThe methods field exists only for functions of type, overloaded.

This field is aseparate MATLAB structure that identifies all overloaded methods that arebound to the function handle.The structure contains one field for each method of the function handle. Thefield names are the classes that overload the function. Each field value is acharacter array holding the path and name of the source file that defines themethod.For example, a function handle for the display function may be bound to theM-files shown below.

The functions command returns a methods structurehaving a field for each class overloading the function: polynom, inline, serial,and avifile. For each class, it shows the path and name of the method sourcefile.f = functions(@display);f.methodsans =polynom: '\home\user4\@polynom\display.m'inline: 'matlabroot\toolbox\matlab\funfun\@inline\display.m'serial: 'matlabroot\toolbox\matlab\iofun\@serial\display.m'avifile: 'matlabroot\toolbox\matlab\iofun\@avifile\display.m'Note The set of methods returned by functions is determined at the time afunction handle is created. This depends on the state of the MATLAB pathand also which functions are in scope when the handle is created.21-16Displaying Function Handle InformationTypes of Function HandlesThe information returned by functions varies depending on the type offunction represented by the function handle.

This section explains what isreturned for each type of function. The categories of function handles are:• Simple function handles• Overloaded function handles• Constructor function handles• Subfunction handles• Private function handlesSimple Function HandlesThese are handles to nonoverloaded MATLAB built-in or M-file functions. Anyfunction handles for which the function type has not yet been determined (e.g.,Java methods, nonexistent functions), also fall into this category.Structure fields:function: function nametype: 'simple'file: 'MATLAB built-in function'path and name of the default M-file(there is no methods field)for built-insfor nonbuilt-insExamples:Using functions on a function handle to a built-in functionfunctions(@ones)ans =function: 'ones'type: 'simple'file: 'MATLAB built-in function'Using functions on a function handle to a nonbuilt-in functionfunctions(@fzero)ans =function: 'fzero'type: 'simple'file: 'matlabroot\toolbox\matlab\funfun\fzero.m'21-1721Function HandlesOverloaded Function HandlesThese are handles to MATLAB built-in or M-file functions that are overloadedimplementations for different classes.Structure fields:function: function nametype: 'overloaded'file: 'MATLAB built-in function'path and name of the default M-filemethods: [1x1 struct]for built-insfor nonbuilt-insExamples:Using functions on a function handle to a built-in functionfunctions(@display)ans =function: 'display'type: 'overloaded'file: 'MATLAB built-in function'methods: [1x1 struct]Using functions on a function handle to a nonbuilt-in functionfunctions(@deblank)ans =function: 'deblank'type: 'overloaded'file: 'matlabroot\toolbox\matlab\strfun\deblank.m'methods: [1x1 struct]Constructor Function HandlesThese are handles to functions that construct objects of MATLAB classes.Structure fields:function:type:file:(there is21-18function name'constructor'path and name of the constructor M-fileno methods field)Displaying Function Handle InformationExample:Using functions on a function handle to a constructor functionfunctions(@inline)ans =function: 'inline'type: 'constructor'file: 'matlabroot\toolbox\matlab\funfun\@inline\inline.m'Subfunction HandlesThese are handles to MATLAB subfunctions, which are functions definedwithin an M-file that are only visible to the primary function of that M-file.When you use functions on a subfunction handle, the file field of the returnstructure contains the path and name of the M-file in which the subfunction isdefined.Structure fields:function:type:file:(there isfunction name'subfunction'path and name of the M-file defining the subfunctionno methods field)Example:The getLocalHandle M-file, shown below, defines a primary function and asubfunction, named subfunc.% -- File GETLOCALHANDLE.M -function subhandle = getLocalHandle()subhandle = @subfunc;% return handle to subfunctionfunction subfunc()disp 'running subfunc'A call to getLocalHandle returns a function handle to the subfunction.

Whenyou pass that handle to functions, it returns the following information.fhandle = getLocalHandle;functions(fhandle)ans =function: 'subfunc'21-1921Function Handlestype: 'subfunction'file: '\home\user4\getLocalHandle.m'Private Function HandlesThese are handles to MATLAB private functions, which are functions definedin a private subdirectory that are only visible to functions in the parentdirectory. When you use functions on a private function handle, the file fieldof the return structure contains the path and name of the M-file in the privatesubdirectory that defines the function.Structure fields:function:type:file:(there isfunction name'private'path and name of the M-file in \privateno methods field)Example:The getPrivateHandle function, shown below, returns a handle to a privatefunction named privatefunc.% -- File GETPRIVATEHANDLE.M -function privhandle = getPrivateHandle()privhandle = @privatefunc;% return handle to private functionThe following function, privatefunc, resides in the \private subdirectory.% -- File \PRIVATE\PRIVATEFUNC.M -function privatefunc()disp 'running privatefunc'A call to getPrivateHandle returns a handle to the function, privatefunc,defined in \private.

When you pass that handle to functions, it returns thefollowing information.fhandle = getPrivateHandle;functions(fhandle)ans =function: 'privatefunc'type: 'private'file: '\home\user4\private\privatefunc.m'21-20Function Handle OperationsFunction Handle OperationsMATLAB provides two functions that enable you to convert between a functionhandle and a function name string. It also provides functions for testing to seeif a variable holds a function handle, and for comparing function handles.Converting Function Handles to Function NamesIf you need to perform string operations, such as string comparison or display,on a function handle, you can use func2str to obtain the function name instring format.

To convert a sin function handle to a stringfhandle = @sin;func2str(fhandle)ans =sinNote The func2str command does not operate on nonscalar functionhandles. Passing a nonscalar function handle to func2str results in an error.Example - Displaying the Function Name in an Error MessageThe catcherr function shown here accepts function handle and dataarguments and attempts to evaluate the function through its handle. If thefunction fails to execute, catcherr uses sprintf to display an error messagegiving the name of the failing function. The function name must be a string forsprintf to display it. The code derives the function name from the functionhandle using func2str.function catcherr(func, data)tryans = feval(func, data);disp('Answer is:');anscatchsprintf('Error executing function ''%s''\n', func2str(func))end21-2121Function HandlesThe first call to catcherr, shown below, passes a handle to the round functionand a valid data argument.

This call succeeds and returns the expectedanswer. The second call passes the same function handle and an improper datatype (a MATLAB structure). This time, round fails, causing catcherr to displayan error message that includes the failing function name.catcherr(@round, 5.432)ans =Answer is 5xstruct.value = 5.432;catcherr(@round, xstruct)Error executing function "round"Converting Function Names to Function HandlesUsing the str2func function, you can construct a function handle from a stringcontaining the name of a MATLAB function.

To convert the string, ’sin’, into ahandle for that functionfh = str2func('sin')fh =@sinIf you pass a function name string in a variable, the function that receives thevariable can convert the function name to a function handle using str2func.The example below passes the variable, funcname, to function makeHandle,which then creates a function handle.function fh = makeHandle(funcname)fh = str2func(funcname);% -- end of makeHandle.m file -makeHandle('sin')ans =@sinYou can also perform the str2func operation on a cell array of function namestrings. In this case, str2func returns an array of function handles.fh_array = str2func({'sin' 'cos' 'tan'})fh_array =@sin@cos@tan21-22Function Handle OperationsExample - More Flexible Parameter CheckingIn the following example, the myminbnd function expects to receive either afunction handle or string in the first argument.

If you pass a string, myminbndconstructs a function handle from it using str2func, and then uses that handlein a call to fminbnd.function myminbnd(fhandle, lower, upper)if ischar(fhandle)disp 'converting function string to function handle ...'fhandle = str2func(fhandle);endfminbnd(fhandle, lower, upper)Whether you call myminbnd with a function handle or function name string, itis able to handle the argument appropriately.myminbnd('humps', 0.3, 1)converting function string to function handle ...ans =0.6370Testing for Data TypeThe isa function identifies the data type or class of a MATLAB variable orobject. You can see if a variable holds a function handle by using isa with thefunction_handle tag. The following function tests an argument passed in tosee if it is a function handle before attempting to evaluate it.function evaluate_handle(arg1, arg2)if isa(arg1, 'function_handle')feval(arg1, arg2);elsedisp 'You need to pass a function handle';endTesting for EqualityYou can use the isequal function to compare two function handles for equality.For example, you want to execute one particular method you have written foran overloaded function.

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

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

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

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