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

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

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

. . . . 14-19Example: Double Integration . . . . . . . . . . . . . 14-2014Function FunctionsAll of the functions described in this chapter are called function functionsbecause they accept a function as an input arguments. You can pass such afunction either as a function handle or as an inline object that defines amathematical function. The function that is passed in is referred to as theobjective function.This chapter includes:Function SummaryA summary of some function functionsRepresenting Functions in MATLABSome guidelines for representing functions in MATLABPlotting Mathematical FunctionsA discussion about using fplot to plot mathematical functionsMinimizing Functions and Finding ZerosA discussion of high-level function functions that perform optimization-relatedtasksNumerical Integration (Quadrature)A discussion of the MATLAB quadrature functionsNote See the “Differential Equations” and “Sparse Matrices” chapters forinformation about the use of other function functions.Note For information about function handles, see the function_handle (@),func2str, and str2func reference pages, and the “Function Handles” sectionof “Programming and Data Types” in the MATLAB documentation.14-2Function SummaryFunction SummaryThe function functions are located in the MATLAB funfun directory.This table provides a brief description of the functions discussed in thischapter.

Related functions are grouped by category.Function SummaryCategoryFunctionDescriptionPlottingfplotPlot function.Optimizationand zero findingfminbndMinimize function of one variable withbound constraints.fminsearchMinimize function of several variables.fzeroFind zero of function of one variable.quadNumerically evaluate integral, adaptiveSimpson quadrature.quadlNumerically evaluate integral, adaptiveLobatto quadrature.dblquadNumerically evaluate double integral.Numericalintegration14-314Function FunctionsRepresenting Functions in MATLABMATLAB can represent mathematical functions by expressing them asMATLAB functions in M-files or as inline objects. For example, consider thefunction11f ( x ) = ------------------------------------------- + ------------------------------------------- – 622( x – 0.3 ) + 0.01 ( x – 0.9 ) + 0.04This function can be used as input to any of the function functions.As MATLAB FunctionsYou can find the function above in the M-file named humps.m.function y = humps(x)y = 1./((x - 0.3).^2 + 0.01) + 1./((x - 0.9).^2 + 0.04) - 6;To evaluate the function humps at 2.0, use @ to obtain a function handle forhumps, and then pass the function handle to feval.fh = @humps;feval(fh,2.0)ans =-4.8552As Inline ObjectsA second way to represent a mathematical function at the command line is bycreating an inline object from a string expression.

For example, you can createan inline object of the humps functionf = inline(‘1./((x-0.3).^2 + 0.01) + 1./((x-0.9).^2 + 0.04)-6’);You can then evaluate f at 2.0.f(2.0)ans =-4.8552You can also create functions of more than one argument with inline byspecifying the names of the input arguments along with the string expression.For example, the following function has two input arguments x and y.14-4Representing Functions in MATLABf= inline('y*sin(x)+x*cos(y)','x','y')f(pi,2*pi)ans =3.141614-514Function FunctionsPlotting Mathematical FunctionsThe fplot function plots a mathematical function between a given set of axeslimits.

You can control the x-axis limits only, or both the x- and y-axis limits.For example, to plot the humps function over the x-axis range [-5 5], usefplot(@humps,[-5 5])grid on100806040200−20−5−4−3−2−1012345You can zoom in on the function by selecting y-axis limits of -10 and 25, usingfplot(@humps,[-5 5 -10 25])grid on14-6Plotting Mathematical Functions2520151050−5−10−5−4−3−2−1012345You can also pass an inline for fplot to graph, as infplot(inline('2*sin(x+3)'),[-1 1])You can plot more than one function on the same graph with one call to fplot.If you use this with a function, then the function must take a column vector xand return a matrix where each column corresponds to each function,evaluated at each value of x.If you pass an inline object of several functions to fplot, the inline object alsomust return a matrix where each column corresponds to each functionevaluated at each value of x, as infplot(inline('[2*sin(x+3), humps(x)]'),[-5 5])which plots the first and second functions on the same graph.14-714Function Functions100806040200−20−5−4−3−2−1012345Note that the inlinef= inline('[2*sin(x+3), humps(x)]')evaluates to a matrix of two columns, one for each function, when x is a columnvector.f([1;2;3])returns-1.5136-1.9178-0.558814-816.0000-4.8552-5.6383Minimizing Functions and Finding ZerosMinimizing Functions and Finding ZerosMATLAB provides a number of high-level function functions that performoptimization-related tasks.

This section describes:• Minimizing a function of one variable• Minimizing a function of several variables• Setting minimization options• Finding a zero of a function of one variable• Converting your code to MATLAB Version 5 syntaxThe MATLAB optimization functions are:fminbndMinimize a function of one variable on a fixed intervalfminsearchMinimize a function of several variablesfzeroFind zero of a function of one variablelsqnonnegLinear least squares with nonnegativity constraintsoptimgetGet optimization options structure parameter valuesoptimsetCreate or edit optimization options parameter structureFor more optimization capabilities, see the Optimization Toolbox.Minimizing Functions of One VariableGiven a mathematical function of a single variable coded in an M-file, you canuse the fminbnd function to find a local minimizer of the function in a giveninterval.

For example, to find a minimum of the humps function in the range(0.3, 1), usex = fminbnd(@humps,0.3,1)which returnsx =0.6370You can ask for a tabular display of output by passing a fourth argumentcreated by the optimset command to fminbnd14-914Function Functionsx = fminbnd(@humps,0.3,1,optimset('Display','iter'))which gives the outputFunc-count123456789x0.5673760.7326240.4652480.6444160.64130.6376180.6369850.6370190.637052f(x)12.909813.774625.171411.269311.258311.252911.252811.252811.2528Procedureinitialgoldengoldenparabolicparabolicparabolicparabolicparabolicparabolicx =0.6370This shows the current value of x and the function value at f(x) each time afunction evaluation occurs.

For fminbnd, one function evaluation correspondsto one iteration of the algorithm. The last column shows what procedure isbeing used at each iteration, either a golden section search or a parabolicinterpolation.Minimizing Functions of Several VariablesThe fminsearch function is similar to fminbnd except that it handles functionsof many variables, and you specify a starting vector x0 rather than a startinginterval. fminsearch attempts to return a vector x that is a local minimizer ofthe mathematical function near this starting vector.To try fminsearch, create a function three_var of three variables, x, y, and z.function b = three_var(v)x = v(1);y = v(2);z = v(3);b = x.^2 + 2.5*sin(y) - z^2*x^2*y^2;Now find a minimum for this function using x = -0.6, y = -1.2, andz = 0.135 as the starting values.v = [-0.6 -1.2 0.135];14-10Minimizing Functions and Finding Zerosa = fminsearch(@three_var,v)a =0.0000-1.57080.1803Setting Minimization OptionsYou can specify control options that set some minimization parameters bycalling fminbnd with the syntaxx = fminbnd(fun,x1,x2,options)or fminsearch with the syntaxx = fminsearch(fun,x0,options)options is a structure used by the optimization functions.

Use optimset to setthe values of the options structure.options = optimset('Display','iter');fminbnd and fminsearch use only the options parameters shown in thefollowing table. See the optimset reference page for a complete list of theparameters that are used in the Optimization Toolbox.options.DisplayA flag that determines if intermediate steps in theminimization appear on the screen. If set to 'iter',intermediate steps are displayed; if set to 'off', nointermediate solutions are displayed, if set to final,displays just the final output.options.TolXThe termination tolerance for x. Its default value is1.e-4.options.TolFunThe termination tolerance for the function value.The default value is 1.e-4.

This parameter is usedby fminsearch, but not fminbnd.options.MaxIterMaximum number of iterations allowed.options.MaxFunEvalsThe maximum number of function evaluationsallowed. The default value is 500 for fminbnd and200*length(x0) for fminsearch.14-1114Function FunctionsThe number of function evaluations, the number of iterations, and thealgorithm are returned in the structure output when you provide fminbnd orfminsearch with a fourth output argument, as in[x,fval,exitflag,output] = fminbnd(@humps,0.3,1);or[x,fval,exitflag,output] = fminsearch(@three_var,v);Finding Zeros of FunctionsThe fzero function attempts to find a zero of one equation with one variable.You can call this function with either a one-element starting point or atwo-element vector that designates a starting interval.

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

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

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

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