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

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

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

See the bvpinit reference page for details.The output argument sol is a structure created by the solver. In the basic casethe structure has fields x, y, and yp.sol.xNodes of the mesh selected by bvp4csol.yApproximation to y ( x ) at the mesh points of sol.xsol.ypApproximation to y′ ( x ) at the mesh points of sol.xsol.parametersValue of unknown parameters, if present, found by thesolver.sol.solver'bvp4c'The function deval uses the output structure sol to evaluate the numericalsolution at any point from [a,b].Additional BVP Solver ArgumentsFor more advanced applications, you can also specify as input arguments solveroptions and additional known parameters.optionsStructure of optional parameters that change the defaultintegration properties.

This is the fourth input argument.sol = bvp4c(odefun,bcfun,solinit,options)“Creating and Maintaining a BVP Options Structure” onpage 15-76 tells you how to create the structure and describesthe properties you can specify.15-62Boundary Value Problems for ODEsp1,p2...Known parameters that the solver passes to odefun and bcfun.sol = bvp4c(odefun,bcfun,solinit,options,p1,p2...)The solver passes any input parameters that follow the optionsargument to odefun and bcfun every time it calls them.

Useoptions = [] as a placeholder if you set no options. In theodefun argument list, known parameters follow x, y, and avector of unknown parameters (parameters), if present.dydx = odefun(x,y,p1,p2,...)dydx = odefun(x,y,parameters,p1,p2,...)In the bcfun argument list, known parameters follow ya, yb,and a vector of unknown parameters, if present.res = bcfun(ya,yb,p1,p2,...)res = bcfun(ya,yb,parameters,p1,p2,...)See “Example: Using Continuation to Solve a Difficult BVP” onpage 15-68 for an example.Representing BVP ProblemsThis section describes:• The process for solving boundary value problems (BVPs) using the MATLABsolver, bvp4c• Finding unknown parameters• Evaluating the solution at specific pointsExample: Mathieu’s EquationThis example determines the fourth eigenvalue of Mathieu’s Equation.

Itillustrates how to write second-order differential equations as a system of twofirst-order ODEs and how to use bvp4c to determine an unknown parameter λ .The task is to compute the fourth ( q = 5 ) eigenvalue λ of Mathieu’s equationy′′ + ( λ – 2 q cos 2x ) y = 0Because the unknown parameter λ is present, this second-order differentialequation is subject to three boundary conditions15-6315Differential Equationsy(0) = 1y′ ( 0 ) = 0y′ ( π ) = 0Note The demo mat4bvp contains the complete code for this example. Thedemo uses subfunctions to place all functions required by bvp4c in a singleM-file. To run this example type mat4bvp at the command line.

See “BVPSolver Basic Syntax” on page 15-61 for more information.1 Rewrite the Problem as a First-Order System. To use bvp4c, you must rewrite theequations as an equivalent system of first-order differential equations. Using asubstitution y 1 = y and y 2 = y′ , the differential equation is written as asystem of two first-order equationsy1 ′ = y2y 2 ′ = – ( λ – 2 q cos 2x ) y 1Note that the differential equations depend on the unknown parameter λ . Theboundary conditions becomey1 ( 0 ) – 1 = 0y2 ( 0 ) = 0y2 ( π ) = 02 Code the System of First-Order ODEs in MATLAB. Once you represent the equationas a first-order system, you can code it as a function that bvp4c can use.Because there is an unknown parameter, the function must be of the formdydx = odefun(x,y,parameters)The code below represents the system in the MATLAB function, mat4ode.function dydx = mat4ode(x,y,lambda)q = 5;dydx = [y(2)-(lambda - 2*q*cos(2*x))*y(1) ];15-64Boundary Value Problems for ODEsSee “Finding Unknown Parameters” on page 15-67 for more information aboutusing unknown parameters with bvp4c.3 Code the Boundary Conditions Function.

You must also code the boundaryconditions in a MATLAB function. Because there is an unknown parameter,the function must be of the formres = bcfun(ya,yb,parameters)The code below represents the boundary conditions in the MATLAB function,mat4bc.function res = mat4bc(ya,yb,lambda)res = [ ya(2)yb(2)ya(1)-1 ];4 Create an Initial Guess.

To form the guess structure solinit with bvpinit, youneed to provide initial guesses for both the solution and the unknownparameter.The function mat4init provides an initial guess for the solution. mat4init usesy = cos 4x because this function satisfies the boundary conditions and has thecorrect qualitative behavior (the correct number of sign changes).function yinit = mat4init(x)yinit = [ cos(4*x)-4*sin(4*x) ];In the call to bvpinit, the third argument, lambda, provides an initial guess forthe unknown parameter λ .lambda = 15;solinit = bvpinit(linspace(0,pi,10),@mat4init,lambda);This example uses @ to pass mat4init as a function handle to bvpinit.Note See the function_handle (@), func2str, and str2func reference pages,and the “Function Handles” chapter of “Programming and Data Types” in theMATLAB documentation for information about function handles.15-6515Differential Equations5 Apply the BVP Solver.

The mat4bvp example calls bvp4c with the functionsmat4ode and mat4bc and the structure solinit created with bvpinit.sol = bvp4c(@mat4ode,@mat4bc,solinit);6 View the Results. Complete the example by displaying the results:• Print the value of the unknown parameter λ found by bvp4c.fprintf('The fourth eigenvalue is approximately %7.3f.\n',...sol.parameters)• Use deval to evaluate the numerical solution at 100 equally spaced points inthe interval [ 0, π ] , and plot its first component. This componentapproximates y ( x ) .xint = linspace(0,pi);Sxint = deval(sol,xint);plot(xint,Sxint(1,:))axis([0 pi -1 1.1])title('Eigenfunction of Mathieu''s equation.')xlabel('x')ylabel('solution y')See “Evaluating the Solution at Specific Points” on page 15-68 for informationabout using deval.The following plot shows the eigenfunction associated with the final eigenvalueλ = 17.097.15-66Boundary Value Problems for ODEsEigenfunction of Mathieu’s equation.10.80.6solution y0.40.20−0.2−0.4−0.6−0.8−100.511.5x22.53Finding Unknown ParametersThe bvp4c solver can find unknown parameters p for problems of the formy′ = f ( x, y, p )bc ( y ( a ), y ( b ), p ) = 0You must provide bvp4c an initial guess for any unknown parameters in thevector solinit.parameters.

When you call bvpinit to create the structuresolinit, specify the initial guess as a vector in the additional argumentparameters.solinit = bvpinit(x,v,parameters)The bvp4c function arguments odefun and bcfun must each have a thirdargument.dydx = odefun(x,y,parameters)res = bcfun(ya,yb,parameters)The bvp4c solver calculates intermediate values of unknown parameters ateach iteration, and passes the latest values to odefun and bcfun in the15-6715Differential Equationsparameters arguments. The solver returns the final values of these unknownparameters in sol.parameters. See “Example: Mathieu’s Equation” onpage 15-63.Evaluating the Solution at Specific PointsThe collocation method implemented in bvp4c produces a C1-continuoussolution over the whole interval of integration [ a, b ] .

You can evaluate theapproximate solution, S ( x ) , at any point in [ a, b ] using the helper functiondeval and the structure sol returned by bvp4c.Sxint = deval(sol,xint)The deval function is vectorized. For a vector xint, the ith column of Sxintapproximates the solution y ( xint(i) ) .Using Continuation to Make a Good Initial GuessTo solve a boundary value problem, you need to provide an initial guess for thesolution. The quality of your initial guess can be critical to the solverperformance, and to being able to solve the problem at all. However, coming upwith a sufficiently good guess can be the most challenging part of solving aboundary value problem.

Certainly, you should apply the knowledge of theproblem's physical origin. Often a problem can be solved as a sequence ofrelatively simpler problems, i.e., a continuation. This section providesexamples that illustrate how to use continuation to:• Solve a difficult BVP.• Verify a solution’s consistent behavior.Example: Using Continuation to Solve a Difficult BVPThis example solves the differential equation2εy″ + xy′ = επ cos ( πx ) – πx sin ( πx )–4for ε = 10 , on the interval [-1 1], with boundary conditions y(– 1) = – 2 andy(1) = 0 . For 0 < ε < 1 , the solution has a transition layer at x = 0 .

Becauseof this rapid change in the solution for small values of ε , the problem becomesdifficult to solve numerically.15-68Boundary Value Problems for ODEsThe example solves the problem as a sequence of relatively simpler problems,i.e., a continuation. The solution of one problem is used as the initial guess forsolving the next problem.Note The demo shockbvp contains the complete code for this example. Thedemo uses subfunctions to place all required functions in a single M-file.

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

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

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

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