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

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

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

For example, if youwant to use the odeplot output function, but you want to plot onlythe first and third components of the solution, you can do thisusingoptions = odeset('OutputFcn',@odeplot,'OutputSel',[1 3]);By default, the solver passes all components of the solution to theoutput function.RefinePositiveintegerIncreases the number of output points by a factor of Refine. IfRefine is 1, the solver returns solutions only at the end of eachtime step.

If Refine is n >1, the solver subdivides each time stepinto n smaller intervals, and returns solutions at each time point.Refine does not apply when length(tspan)>2.Note In all the solvers, the default value of Refine is 1. Withinode45, however, the default is 4 to compensate for the solver’s largestep sizes. To override this and see only the time steps chosen byode45, set Refine to 1.The extra values produced for Refine are computed by means ofcontinuous extension formulas.

These are specialized formulasused by the ODE solvers to obtain accurate solutions betweencomputed time steps without significant increase in computationtime.15-22Initial Value Problems for ODEs and DAEsODE Solver Output Properties (Continued)PropertyValueDescriptionStatson | {off}Specifies whether the solver should display statistics about itscomputations. By default, Stats is off. If it is on, after solving theproblem the solver displays:• The number of successful steps• The number of failed attempts• The number of times the ODE function was called to evaluatef(t, y)• The number of times that the partial derivatives matrix ∂f ⁄ ∂ywas formed• The number of LU decompositions• The number of solutions of linear systemsJacobian Matrix PropertiesThe stiff ODE solvers often execute faster if you provide additional informationabout the Jacobian matrix ∂f ⁄ ∂y , a matrix of partial derivatives of the functionthat defines the differential equations.∂f 1 ∂f 1-------- -------- …∂y 1 ∂ y 2∂f------ =∂y∂f 2 ∂ f 2-------- -------- …∂y 1 ∂ y 2……The Jacobian matrix properties pertain only to those solvers for stiff problems(ode15s, ode23s, ode23t, and ode23tb) for which the Jacobian matrix ∂f ⁄ ∂ycan be critical to reliability and efficiency.

If you do not provide a function tocalculate the Jacobian, these solvers approximate the Jacobian numericallyusing finite differences. In this case, you may want to use the Vectorized, orJPattern properties.15-2315Differential EquationsThe following table describes the Jacobian matrix properties. Use odeset to setthese properties.ODE Jacobian Matrix PropertiesPropertyValueDescriptionJacobianFunction |constant matrixA constant matrix or a function that evaluates the Jacobian.Supplying an analytical Jacobian often increases the speedand reliability of the solution for stiff problems.

Set thisproperty to a function FJac, where FJac(t,y) computes ∂f ⁄ ∂y ,or to the constant value of ∂f ⁄ ∂y .The Jacobian for the stiff van der Pol problem shown above canbe coded asfunction J = vdp1000jac(t,y)J = [ 01(-2000*y(1)*y(2)-1) (1000*(1-y(1)^2)) ];JPatternSparse matrixof {0,1}Sparsity pattern with 1s where there might be nonzero entriesin the Jacobian. It is used to generate a sparse Jacobianmatrix numerically.Set this property to a sparse matrix S with S(i, j) = 1 ifcomponent i of f(t, y) depends on component j of y , and 0otherwise.

The solver uses this sparsity pattern to generate asparse Jacobian matrix numerically. If the Jacobian matrix islarge and sparse, this can greatly accelerate execution. For anexample using the JPattern property, see “Example: Large,Stiff Sparse Problem” on page 15-38 (brussode).15-24Initial Value Problems for ODEs and DAEsODE Jacobian Matrix Properties (Continued)PropertyValueDescriptionVectorizedon | {off}Set on to inform the solver that you have coded the ODEfunction F so that F(t,[y1 y2 ...]) returns[F(t,y1) F(t,y2) ...]. This allows the solver to reduce thenumber of function evaluations required to compute all thecolumns of the Jacobian matrix, and may significantly reducesolution time.With MATLAB’s array notation, it is typically an easy matterto vectorize an ODE function.

For example, the stiff van derPol example shown previously can be vectorized by introducingcolon notation into the subscripts and by using the arraypower (.^) and array multiplication (.*) operators.function dydt = vdp1000(t,y)dydt = [y(2,:); 1000*(1-y(1,:).^2).*y(2,:)-y(1,:)];Note Vectorization of the ODE function used by the ODEsolvers differs from the vectorization used by the BVP solver,bvp4c. For the ODE solvers, the ODE function is vectorizedonly with respect to the second argument, while bvp4crequires vectorization with respect the first and secondarguments.Step-Size PropertiesThe step-size properties let you specify the size of the first step the solver tries,potentially helping it to better recognize the scale of the problem. In addition,you can specify bounds on the sizes of subsequent time steps.15-2515Differential EquationsThe following table describes the step-size properties.

Use odeset to set theseproperties.ODE Step Size PropertiesPropertyValueDescriptionInitialStepPositive scalarSuggested initial step size. InitialStep sets an upperbound on the magnitude of the first step size the solvertries. If you do not set InitialStep, the initial step size isbased on the slope of the solution at the initial timetspan(1), and if the slope of all solution components iszero, the procedure might try a step size that is much toolarge. If you know this is happening or you want to besure that the solver resolves important behavior at thestart of the integration, help the code start by providing asuitable InitialStep.MaxStepPositive scalar{0.1∗abs(t0-tf)}Upper bound on solver step size.

If the differentialequation has periodic coefficients or solutions, it may be agood idea to set MaxStep to some fraction (such as 1/4) ofthe period. This guarantees that the solver does notenlarge the time step too much and step over a period ofinterest. Do not reduce MaxStep:• To produce more output points. This can significantlyslow down solution time. Instead, use Refine to computeadditional outputs by continuous extension at very lowcost.• When the solution does not appear to be accurateenough. Instead, reduce the relative error toleranceRelTol, and use the solution you just computed todetermine appropriate values for the absolute errortolerance vector AbsTol. (See “Error Control Properties”on page 15-18 for a description of the error toleranceproperties.)15-26Initial Value Problems for ODEs and DAEsODE Step Size Properties (Continued)PropertyValueDescription• To make sure that the solver doesn’t step over somebehavior that occurs only once during the simulationinterval.

If you know the time at which the changeoccurs, break the simulation interval into two pieces andcall the solvers twice. If you do not know the time atwhich the change occurs, try reducing the errortolerances RelTol and AbsTol. Use MaxStep as a lastresort.Mass Matrix and DAE PropertiesThe solvers of the ODE suite can solve ODEs of the formM(t, y) y′ = f(t, y)(15-2)with a mass matrix M ( t, y ) that can be sparse.When M ( t, y ) is nonsingular, the equation above is equivalent to–1y′ = M f ( t, y ) and the ODE has a solution for any initial values y 0 at t 0 . Themore general form (Equation 15-2) is convenient when you express a modelnaturally in terms of a mass matrix.

For large, sparse M ( t, y ) , solvingEquation 15-2 directly reduces the storage and runtime needed to solve theproblem.When M ( t, y ) is singular, then M(t, y) y′ = f(t, y) is a differential-algebraicequation (DAE). A DAE has a solution only when y 0 is consistent, that is, thereexists an initial slope yp 0 such that M ( t 0, y 0 )yp 0 = f(t 0, y 0) . If y 0 and yp 0are not consistent, the solver treats them as guesses, attempts to computeconsistent values that are close to the guesses, and continues to solve theproblem.

For DAEs of index 1, solving an initial value problem with consistentinitial conditions is much like solving an ODE.The ode15s and ode23t solvers can solve DAEs of index 1. For examples of DAEproblems, see hb1dae (“Example: Differential-Algebraic Problem” onpage 15-47) and amp1dae.15-2715Differential EquationsThe following table describes the mass matrix and DAE properties.

Use odesetto set these properties.ODE Mass Matrix and DAE PropertiesPropertyValueDescriptionMassConstant matrix |functionConstant mass matrix or a function that evaluatesthe mass matrix M ( t, y ) . For problemsMy′ = f ( t, y ) set this property to the value of theconstant mass matrix M . For problemsM(t, y) y′ = f(t, y) , set this property to a functionMfun, where Mfun(t,y) evaluates the mass matrixM ( t, y ) . When solving DAEs, it is advantageous toformulate the problem so that M is a diagonalmatrix (a semi-explicit DAE). The ode23s solvercan only solve problems with a constant massmatrix M .For example problems, see fem1ode (“Example:Finite Element Discretization” on page 15-35),fem2ode, or batonode.15-28MStateDependencenone | {weak} |strongDependence of the mass matrix on y .

Set thisproperty to none for problems M(t) y′ = f(t, y) .Both weak and strong indicate M ( t, y ) , but weakresults in implicit solvers using approximationswhen solving algebraic equations.MvPatternSparse matrix∂ ( M ( t, y )v ) ⁄ ∂y sparsity pattern. Set this propertyto a sparse matrix S with S ( i, j ) = 1 if for any k ,the ( i, k ) component of M ( t, y ) depends oncomponent j of y , and 0 otherwise. For use with theode15s, ode23t, and ode23tb solvers whenMStateDependence is strong. See burgersode as anexample.Initial Value Problems for ODEs and DAEsODE Mass Matrix and DAE Properties (Continued)PropertyValueDescriptionMassSingularyes | no |{maybe}Indicates whether the mass matrix is singular. Setthis property to no if the mass matrix is notsingular and you are using either the ode15s orode23t solver.

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

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

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

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