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

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

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

The bigger the value of Refine, the moreoutput points. Execution speed is not affected much by the valueof Refine.15-5515Differential EquationsTroubleshooting (Continued)QuestionAnswerI’m plotting the solution asit is computed and it looksfine, but the code gets stuckat some point.First verify that the ODE function is smooth near the pointwhere the code gets stuck.

If it isn’t, the solver must take smallsteps to deal with this. It may help to break tspan into pieces onwhich the ODE function is smooth.If the function is smooth and the code is taking extremely smallsteps, you are probably trying to solve a stiff problem with asolver not intended for this purpose. Switch to ode15s, ode23s,ode23t, or ode23tb.My integration proceedsvery slowly, using too manytime steps.First, check that your tspan is not too long. Remember that thesolver uses as many time points as necessary to produce a smoothsolution. If the ODE function changes on a time scale that is veryshort compared to the tspan, the solver uses a lot of time steps.Long-time integration is a hard problem.

Break tspan intosmaller pieces.If the ODE function does not change noticeably on the tspaninterval, it could be that your problem is stiff. Try using ode15s,ode23s, ode23t, or ode23tb.Finally, make sure that the ODE function is written in anefficient way. The solvers evaluate the derivatives in the ODEfunction many times. The cost of numerical integration dependscritically on the expense of evaluating the ODE function. Ratherthan recompute complicated constant parameters at eachevaluation, store them in globals or calculate them once outsidethe function and pass them in as additional parameters.I know that the solutionundergoes a radical changeat time t wheret0 ≤ t ≤ tfbut the integrator stepspast without “seeing” it.15-56If you know there is a sharp change at time t, it might help tobreak the tspan interval into two pieces, [t0 t] and [t tf], andcall the integrator twice.If the differential equation has periodic coefficients or solution,you might restrict the maximum step size to the length of theperiod so the integrator won’t step over periods.Boundary Value Problems for ODEsBoundary Value Problems for ODEsThis section describes how to use MATLAB to solve boundary value problems(BVPs) of ordinary differential equations (ODEs).

It provides:• A summary of the MATLAB BVP functions and examples• An introduction to BVPs• A description of the BVP solver and its syntax• General instructions for representing a BVP in MATLAB• A discussion and examples about using continuation to solve a difficultproblem• A discussion about changing default integration properties to improve solverperformanceBVP Function SummaryODE Boundary Value Problem SolverSolverDescriptionbvp4cSolve two-point boundary value problems for ordinarydifferential equations.BVP Helper FunctionsFunctionDescriptionbvpinitForm the initial guess for bvp4c.devalEvaluate the numerical solution using the output of bvp4c.15-5715Differential EquationsBVP Option HandlingAn options structure contains named properties whose values are passed to thesolver, and which affect problem solution.

Use these functions to create, alter,or access an options structure.FunctionDescriptionbvpsetCreate/alter the BVP options structure.bvpgetExtract properties from options structure created with bvpset.ODE Boundary Value Problem ExamplesThese examples illustrate the kind of problems you can solve using theMATLAB BVP solver. From the MATLAB Help browser, click the examplename to see the code in an editor. Type the example name at the command lineto run it.Note The Differential Equations Examples browser enables you to view thecode for the BVP examples, and also run them.

Click on the link to invoke thebrowser, or type odeexamples('bvp')at the command line.ExampleDescriptionfsbvpFalkner-Skan BVP on an infinite intervalmat4bvpFourth eigenfunction of Mathieu’s equationshockbvpSolution with a shock layer near x = 0twobvpBVP with exactly two solutionsAdditional examples are provided with the tutorial by Shampine, Reichelt, andKierzenka, “Solving Boundary Value Problems for Ordinary DifferentialEquations in MATLAB with bvp4c.” The tutorial and the examples areavailable at ftp://ftp.mathworks.com/pub/doc/papers/bvp/. This tutorialillustrates techniques for solving nontrivial real-life problems.15-58Boundary Value Problems for ODEsIntroduction to Boundary Value ODE ProblemsThe BVP solver is designed to handle systems of ordinary differentialequationsy′ = f ( x, y )where x is the independent variable, y is the dependent variable, and y′represents dy ⁄ dx .See “What Is an Ordinary Differential Equation” on page 15-6 for generalinformation about ODEs.Using Boundary Conditions to Specify the Solution of InterestIn a boundary value problem, the solution of interest satisfies certain boundaryconditions.

These conditions specify a relationship between the values of thesolution at more than one x . bvp4c is designed to solve two-point BVPs, i.e.,problems where the solution sought on an interval [ a, b ] must satisfy theboundary conditionsg(y(a), y(b)) = 0Unlike initial value problems, a boundary value problem may not have asolution, may have a finite number of solutions, or may have infinitely manysolutions.

As an integral part of the process of solving a BVP, you need toprovide a guess for the required solution. The quality of this guess can becritical for the solver performance and even for a successful computation.There may be other difficulties when solving BVPs, such as problems imposedon infinite intervals or problems that involve singular coefficients. Often BVPsinvolve unknown parameters p that have to be determined as part of solvingthe problemy′ = f ( x, y, p )g(y(a), y(b), p) = 0In this case, the boundary conditions must suffice to determine the value of p .15-5915Differential EquationsBoundary Value Problem SolverThis section describes:• The BVP solver, bvp4c• BVP solver basic syntax• Additional BVP solver argumentsYou can also use the MATLAB Help browser to get information about thesyntax for MATLAB functions.The BVP SolverThe function bvp4c solves two-point boundary value problems for ordinarydifferential equations (ODEs).

It integrates a system of first-order ordinarydifferential equationsy′ = f ( x, y )on the interval [ a, b ] , subject to general two-point boundary conditionsbc ( y ( a ), y ( b ) ) = 0It can also accommodate unknown parameters for problems of the formy′ = f ( x, y, p )bc ( y ( a ), y ( b ), p ) = 0In this case, the number of boundary conditions must be sufficient to determinethe solution and the unknown parameters. For more information, see “FindingUnknown Parameters” on page 15-67.bvp4c produces a solution that is continuous on [ a, b ] and has a continuousfirst derivative there. You can use the function deval and the output of bvp4cto evaluate the solution at specific points on the interval of integration.bvp4c is a finite difference code that implements the 3-stage Lobatto IIIaformula.

This is a collocation formula and the collocation polynomial providesa C1-continuous solution that is fourth-order accurate uniformly in the intervalof integration. Mesh selection and error control are based on the residual of thecontinuous solution.The collocation technique uses a mesh of points to divide the interval ofintegration into subintervals. The solver determines a numerical solution by15-60Boundary Value Problems for ODEssolving a global system of algebraic equations resulting from the boundaryconditions, and the collocation conditions imposed on all the subintervals. Thesolver then estimates the error of the numerical solution on each subinterval.If the solution does not satisfy the tolerance criteria, the solver adapts themesh and repeats the process.

The user must provide the points of the initialmesh as well as an initial approximation of the solution at the mesh points.BVP Solver Basic SyntaxThe basic syntax of the BVP solver issol = bvp4c(odefun,bcfun,solinit)The input arguments are:odefunFunction that evaluates the differential equations. It has the basicformdydx = odefun(x,y)where x is a scalar, and dydx and y are column vectors. odefun canalso accept a vector of unknown parameters and a variable numberof known parameters.bcfunFunction that evaluates the residual in the boundary conditions. Ithas the basic formres = bcfun(ya,yb)where ya and yb are column vectors representing y(a) and y(b),and res is a column vector of the residual in satisfying the boundaryconditions. bcfun can also accept a vector of unknown parametersand a variable number of known parameters.solinit Structure with fields x and y:xOrdered nodes of the initial mesh.

Boundary conditions areimposed at a = solinit.x(1) and b = solinit.x(end).yInitial guess for the solution with solinit.y(:,i) a guessfor the solution at the node solinit.x(i).15-6115Differential EquationsThe structure can have any name, but the fields must be named xand y. It can also contain a vector that provides an initial guess forunknown parameters. You can form solinit with the helperfunction bvpinit.

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

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

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

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