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

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

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

The elements are arranged inthe order[X(1,1)*YX(1,2)*YX(m,1)*YX(m,2)*Y. . .. . .. . .X(1,n)*YX(m,n)*Y]The Kronecker product is often used with matrices of zeros and ones to buildup repeated copies of small matrices. For example, if X is the 2-by-2 matrixX =1324and I = eye(2,2) is the 2-by-2 identity matrix, then the two matriceskron(X,I)andkron(I,X)11-1111Matrices and Linear Algebraare10300103204002041300240000130024andVector and Matrix NormsThe p-norm of a vector xx p = Σpxi 1⁄pis computed by norm(x,p). This is defined by any value of p > 1, but the mostcommon values of p are 1, 2, and ∞ .

The default value is p = 2, whichcorresponds to Euclidean length.[norm(v,1) norm(v) norm(v,inf)]ans =3.00002.23612.0000The p-norm of a matrix A,Ax p-------------A p = maxxx pcan be computed for p = 1, 2, and ∞ by norm(A,p). Again, the default value isp = 2.[norm(C,1) norm(C) norm(C,inf)]ans =19.000011-1214.801513.0000Solving Linear Systems of EquationsSolving Linear Systems of EquationsThis section describes:• The general solution of systems of linear equations• The solution of square systems• The solution of overdetermined systems• The solution of underdetermined systemsOverviewOne of the most important problems in technical computing is the solution ofsimultaneous linear equations.

In matrix notation, this problem can be statedas follows.Given two matrices A and B, does there exist a unique matrix X so that AX = Bor XA = B?It is instructive to consider a 1-by-1 example.Does the equation7x = 21have a unique solution ?The answer, of course, is yes. The equation has the unique solution x = 3. Thesolution is easily obtained by division.x = 21 ⁄ 7 = 3The solution is not ordinarily obtained by computing the inverse of 7, that is7-1 = 0.142857…, and then multiplying 7-1 by 21. This would be more work and,if 7-1 is represented to a finite number of digits, less accurate. Similarconsiderations apply to sets of linear equations with more than one unknown;MATLAB solves such equations without computing the inverse of the matrix.Although it is not standard mathematical notation, MATLAB uses the divisionterminology familiar in the scalar case to describe the solution of a generalsystem of simultaneous equations.

The two division symbols, slash, /, and11-1311Matrices and Linear Algebrabackslash, \, are used for the two situations where the unknown matrixappears on the left or right of the coefficient matrix.X = A\BDenotes the solution to the matrix equation AX = B.X = B/ADenotes the solution to the matrix equation XA = B.You can think of “dividing” both sides of the equation AX = B or XA = B by A.The coefficient matrix A is always in the “denominator.”The dimension compatibility conditions for X = A\B require the two matrices Aand B to have the same number of rows.

The solution X then has the samenumber of columns as B and its row dimension is equal to the column dimensionof A. For X = B/A, the roles of rows and columns are interchanged.In practice, linear equations of the form AX = B occur more frequently thanthose of the form XA = B. Consequently, backslash is used far more frequentlythan slash. The remainder of this section concentrates on the backslashoperator; the corresponding properties of the slash operator can be inferredfrom the identity(B/A)' = (A'\B')The coefficient matrix A need not be square. If A is m-by-n, there are threecases.m=nSquare system. Seek an exact solution.m>nOverdetermined system.

Find a least squares solution.m<nUnderdetermined system. Find a basic solution with at most mnonzero components.The backslash operator employs different algorithms to handle different kindsof coefficient matrices. The various cases, which are diagnosed automaticallyby examining the coefficient matrix, include:• Permutations of triangular matrices• Symmetric, positive definite matrices• Square, nonsingular matrices• Rectangular, overdetermined systems• Rectangular, underdetermined systems11-14Solving Linear Systems of EquationsSquare SystemsThe most common situation involves a square coefficient matrix A and a singleright-hand side column vector b. The solution, x = A\b, is then the same sizeas b. For example,x = A\ux =10-125It can be confirmed that A*x is exactly equal to u.If A and B are square and the same size, then X = A\B is also that size.X = A\BX =19-176-340-113-6It can be confirmed that A*X is exactly equal to B.Both of these examples have exact, integer solutions.

This is because thecoefficient matrix was chosen to be pascal(3), which has a determinant equalto one. A later section considers the effects of roundoff error inherent in morerealistic computation.A square matrix A is singular if it does not have linearly independent columns.If A is singular, the solution to AX = B either does not exist, or is not unique.The backslash operator, A\B, issues a warning if A is nearly singular and raisesan error condition if exact singularity is detected.Overdetermined SystemsOverdetermined systems of simultaneous linear equations are oftenencountered in various kinds of curve fitting to experimental data.

Here is ahypothetical example. A quantity y is measured at several different values oftime, t, to produce the following observations.11-1511Matrices and Linear Algebraty0.00.820.30.720.80.631.10.601.60.552.30.50This data can be entered into MATLAB with the statementst = [0 .3 .8 1.1 1.6 2.3]';y = [.82 .72 .63 .60 .55 .50]';The data can be modeled with a decaying exponential function.y ( t ) ≈ c1 + c2 e–tThis equation says that the vector y should be approximated by a linearcombination of two other vectors, one the constant vector containing all onesand the other the vector with components e-t.

The unknown coefficients, c1 andc2, can be computed by doing a least squares fit, which minimizes the sum ofthe squares of the deviations of the data from the model. There are sixequations in two unknowns, represented by the 6-by-2 matrix.E = [ones(size(t)) exp(-t)]E =1.00001.00001.00001.00001.00001.000011-161.00000.74080.44930.33290.20190.1003Solving Linear Systems of EquationsThe least squares solution is found with the backslash operator.c = E\yc =0.47600.3413In other words, the least squares fit to the data isy ( t ) ≈ 0.4760 + 0.3413 e–tThe following statements evaluate the model at regularly spaced increments int, and then plot the result, together with the original data.T = (0:0.1:2.5)';Y = [ones(size(T)) exp(-T)]*c;plot(T,Y,'-',t,y,'o')You can see that E*c is not exactly equal to y, but that the difference might wellbe less than measurement errors in the original data.A rectangular matrix A is rank deficient if it does not have linearly independentcolumns.

If A is rank deficient, the least squares solution to AX = B is notunique. The backslash operator, A\B, issues a warning if A is rank deficient andproduces a basic solution that has as few nonzero elements as possible.11-1711Matrices and Linear Algebra0.90.850.80.750.70.650.60.550.500.511.522.5Underdetermined SystemsUnderdetermined linear systems involve more unknowns than equations.When they are accompanied by additional constraints, they are the purview oflinear programming.

By itself, the backslash operator deals only with theunconstrained system. The solution is never unique. MATLAB finds a basicsolution, which has at most m nonzero components, but even this may not beunique. The particular solution actually computed is determined by the QRfactorization with column pivoting (see a later section on the QR factorization).11-18Solving Linear Systems of EquationsHere is a small, random example.R = fix(10*rand(2,4))R =63857431b = fix(10*rand(2,1))b =12The linear system Rx = b involves two equations in four unknowns.

Since thecoefficient matrix contains small integers, it is appropriate to use the formatcommand to display the solution in rational format. The particular solution isobtained withformat ratp = R\bp =05/70-11/7One of the nonzero components is p(2) because R(:,2) is the column of R withlargest norm. The other nonzero component is p(4) because R(:,4) dominatesafter R(:,2) is eliminated.The complete solution to the overdetermined (overdetermined?) system can becharacterized by adding an arbitrary vector from the null space, which can befound using the null function with an option requesting a “rational” basis.Z = null(R,'r')Z =-1/2-1/2-7/61/211-1911Matrices and Linear Algebra1001It can be confirmed that R*Z is zero and that any vector x wherex = p + Z*qfor an arbitrary vector q satisfies R*x = b.11-20Inverses and DeterminantsInverses and DeterminantsThis section provides:• An overview of the use of inverses and determinants for solving squarenonsingular systems of linear equations• A discussion of the Moore-Penrose pseudoinverse for solving rectangularsystems of linear equationsOverviewIf A is square and nonsingular, the equations AX = I and XA = I have the samesolution, X.

This solution is called the inverse of A, is denoted by A-1, and iscomputed by the function inv. The determinant of a matrix is useful intheoretical considerations and some types of symbolic computation, but itsscaling and roundoff error properties make it far less satisfactory for numericcomputation. Nevertheless, the function det computes the determinant of asquare matrix.A = pascal(3)A =111123136-35-21-21d = det(A)X = inv(A)d =1X =3-31Again, because A is symmetric, has integer elements, and has determinantequal to one, so does its inverse. On the other hand,B = magic(3)11-2111Matrices and Linear AlgebraB =834159672d = det(B)X = inv(B)d =-360X =0.1472-0.0611-0.0194-0.14440.02220.18890.06390.1056-0.1028Closer examination of the elements of X, or use of format rat, would revealthat they are integers divided by 360.If A is square and nonsingular, then without roundoff error, X = inv(A)*Bwould theoretically be the same as X = A\B and Y = B*inv(A) wouldtheoretically be the same as Y = B/A.

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

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

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

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