RUОт векторов к матрице
День 9 дал скалярное произведение и квадрат нормы. День 10 дал определители и преобразования строк. Здесь соединяем эти умения: сначала строим матрицу из векторов, затем работаем с ней обычными методами.
Вектор-столбец $u$ размера $n$ имеет $n$ строк и один столбец. Транспонирование $v^T$ превращает столбец в строку. Умножение матриц возможно, когда внутренние размеры совпадают.
У произведения $(n\times1)(1\times n)$ результат имеет размер $n\times n$. У произведения $(1\times n)(n\times1)$ результат имеет размер $1\times1$, то есть одно число. Поэтому $uv^T$ и $v^Tu$ — разные объекты.
Внешнее произведение
Внешнее произведение $uv^T$ определяется поэлементно: элемент строки $i$, столбца $j$ равен $u_i v_j$. Каждая строка — строка $v^T$, умноженная на свою координату $u_i$.
$$u=\begin{pmatrix}1\\2\end{pmatrix},\quad v=\begin{pmatrix}3\\-1\end{pmatrix},\quad uv^T=\begin{pmatrix}3&-1\\6&-2\end{pmatrix},\quad v^Tu=1.$$Проверьте, например, второй ряд: $2(3,-1)=(6,-2)$. Если получилась одна строка или одно число вместо квадратной матрицы, ошибка произошла до определения и обращения матрицы — вернитесь к размерам.
Единичная матрица $I$ имеет единицы на диагонали и нули вне неё. Поэтому $I+uv^T$ получается добавлением единицы только к диагональным элементам внешнего произведения.
$$I+uv^T=\begin{pmatrix}4&-1\\6&-1\end{pmatrix}.$$Матрица внешнего произведения имеет зависимые строки, но добавление $I$ меняет ситуацию. Нельзя заключать, что $I+uv^T$ вырождена, только потому что вырождено $uv^T$. В примере определитель равен $2$, а не нулю.
След и определитель отвечают на разные вопросы
След квадратной матрицы — сумма её диагональных элементов: $\tr A=\sum_i A_{ii}$. В приведённом примере след равен $4+(-1)=3$. Определитель равен $4(-1)-(-1)6=2$. Эти операции нельзя заменять друг другом.
Для матрицы порядка $3$ можно раскрыть определитель по строке или получить треугольную матрицу. Напоминание: прибавление кратной другой строки не меняет определитель; обмен двух строк меняет знак; умножение строки на число умножает определитель на это число.
Выбирайте строку с нулями, если она есть. Если нулей нет, короткие вычитания строк часто создают их. После преобразований определитель треугольной матрицы равен произведению диагонали с учётом уже вынесенных множителей и знаков.
Что означает обратная матрица
Матрица $B$ обратна к $A$, если $AB=BA=I$. Она отменяет действие $A$: из $Ax=b$ получаем $x=A^{-1}b$. Для квадратной матрицы обратная существует ровно при $\det A\ne0$.
Вычислить обратную матрицу можно, решив системы $Az_j=e_j$ для всех единичных столбцов $e_j$. Решение $z_j$ становится столбцом $j$ обратной матрицы, потому что умножение $A$ на этот столбец должно дать столбец $j$ единичной матрицы.
Важно сохранять ориентацию: решения этих систем кладутся столбцами, а не строками. Условие $AA^{-1}=I$ проверяет сразу все столбцы.
Метод Гаусса для всех правых частей сразу
Пишем расширенную матрицу $[A\mid I]$. Строковые действия выполняем сразу над всей строкой, включая правую половину. Цель — превратить левую половину в $I$, а не просто в треугольную матрицу. Тогда справа появится $A^{-1}$.
Почему это работает? Каждое действие преобразует эквивалентную систему, одновременно для всех правых частей. Когда слева единичные коэффициенты, справа уже записаны решения этих систем — нужные столбцы обратной матрицы.
Разберём небольшой пример с $A=\begin{pmatrix}2&1\\1&1\end{pmatrix}$. Сначала поменяем строки, чтобы ведущий элемент стал единицей.
$$\left[\begin{array}{cc|cc}2&1&1&0\\1&1&0&1\end{array}\right]\ \longrightarrow\ \left[\begin{array}{cc|cc}1&1&0&1\\2&1&1&0\end{array}\right].$$Теперь $R_2\leftarrow R_2-2R_1$, затем $R_2\leftarrow-R_2$, затем $R_1\leftarrow R_1-R_2$. Получается
$$\left[\begin{array}{cc|cc}1&0&1&-1\\0&1&-1&2\end{array}\right],\qquad A^{-1}=\begin{pmatrix}1&-1\\-1&2\end{pmatrix}.$$След обратной матрицы здесь $1+2=3$. Это не $1/\tr A$: обратное число к сумме не равно сумме диагонали обратной матрицы. Проверим умножением: первая строка произведения равна $(2-1,-2+2)=(1,0)$, вторая — $(1-1,-1+2)=(0,1)$.
Для порядка $3$ алгоритм тот же: последовательно получаем ведущие единицы в трёх столбцах и обнуляем всё над и под ними. Если ведущий элемент ноль, ищем ненулевой ниже и меняем строки. Если такого нет, проверяем вырожденность; делить на ноль нельзя.
Элементарная проверка для внешнего произведения
Действие матрицы можно записать без всех элементов: $(I+uv^T)x=x+u(v^Tx)$. Выражение в скобках $v^Tx$ — одно число. Оно показывает, что добавка всегда направлена вдоль $u$.
Это помогает проверять найденную обратную матрицу по столбцам: для каждого столбца $z_j$ убедитесь, что $z_j+u(v^Tz_j)=e_j$. Никакой новой формулы обращения для этого не нужно.
Необязательное сокращение после освоения Гаусса
Для квадратного обновления единичной матрицы верно $\det(I+uv^T)=1+v^Tu$. Это частный случай леммы об определителе. Область применения здесь: $u,v$ — столбцы одинаковой длины, а базовая матрица именно $I$.
Положим $c=v^Tu$. Если $1+c\ne0$, можно проверить умножением
$$ (I+uv^T)^{-1}=I-\frac{uv^T}{1+c}. $$При раскрытии произведения используем $(uv^T)(uv^T)=u(v^Tu)v^T=cuv^T$. Коэффициент при добавке становится $1-1/(1+c)-c/(1+c)=0$. Это формула Шермана—Моррисона в частном случае, доказанная обычным умножением.
При $1+c=0$ формула не определена и обратной матрицы нет: $(I+uv^T)u=(1+c)u=0$, причём $u\ne0$. Не пытайтесь «сократить» нулевой знаменатель. Названия этих формул запоминать не требуется; все обязательные задачи решаются методом Гаусса.
Сохранить навык работы с нормой
Векторная задача Q7 требует другого действия: квадрат длины раскрывается как скалярное произведение суммы на себя.
$$\|au+bv\|^2=a^2\|u\|^2+b^2\|v\|^2+2ab\|u\|\|v\|\cos\varphi.$$Смешанное слагаемое сохраняет знак $ab\cos\varphi$. После вычисления берём неотрицательный квадратный корень. Угол в $120$ градусов даёт отрицательный косинус; это не повод менять знак всего квадрата.
Последняя проверка: искомая длина должна лежать между $\big||a|\|u\|-|b|\|v\|\big|$ и $|a|\|u\|+|b|\|v\|$. Если она вне этих границ, проверьте смешанное слагаемое и последний корень.
ENFrom vectors to a matrix
Day 9 introduced dot products and squared norms. Day 10 introduced determinants and row operations. Here we combine those skills: construct a matrix from vectors, then use ordinary matrix methods.
A column vector $u$ of size $n$ has $n$ rows and one column. Transposing $v$ produces a row $v^T$. Matrix multiplication is defined when the inner dimensions agree.
The product $(n\times1)(1\times n)$ has size $n\times n$. The product $(1\times n)(n\times1)$ has size $1\times1$, a single number. Thus $uv^T$ and $v^Tu$ are different objects.
The outer product
The outer product $uv^T$ is defined entry by entry: the entry in row $i$, column $j$ is $u_i v_j$. Each row is $v^T$ multiplied by the corresponding coordinate $u_i$.
$$u=\begin{pmatrix}1\\2\end{pmatrix},\quad v=\begin{pmatrix}3\\-1\end{pmatrix},\quad uv^T=\begin{pmatrix}3&-1\\6&-2\end{pmatrix},\quad v^Tu=1.$$Check the second row, for example: $2(3,-1)=(6,-2)$. If you obtained a row or a scalar instead of a square matrix, the error happened before determinant or inverse calculations; return to the dimensions.
The identity matrix $I$ has ones on its diagonal and zeros elsewhere. To form $I+uv^T$, add one only to the diagonal entries of the outer product.
$$I+uv^T=\begin{pmatrix}4&-1\\6&-1\end{pmatrix}.$$The outer-product matrix has dependent rows, but adding $I$ changes the situation. You cannot conclude that $I+uv^T$ is singular just because $uv^T$ is singular. In the example, the determinant is $2$, not zero.
Trace and determinant answer different questions
The trace of a square matrix is the sum of its diagonal entries: $\tr A=\sum_i A_{ii}$. In the example the trace is $4+(-1)=3$, while the determinant is $4(-1)-(-1)6=2$. These are different operations.
For a matrix of order $3$, expand the determinant along a row or reduce it to triangular form. Recall: adding a multiple of another row preserves the determinant; swapping two rows changes its sign; multiplying a row by a number multiplies the determinant by that number.
Choose a row containing zeros when one is available. Otherwise, short row subtractions often create them. After reduction, multiply the diagonal entries of the triangular matrix, keeping track of any factors or sign changes already introduced.
What an inverse matrix means
A matrix $B$ is the inverse of $A$ if $AB=BA=I$. It undoes the action of $A$: from $Ax=b$, we obtain $x=A^{-1}b$. A square matrix has an inverse exactly when $\det A\ne0$.
To calculate an inverse, solve $Az_j=e_j$ for each unit column $e_j$. The solution $z_j$ becomes column $j$ of the inverse, because multiplying it by $A$ must produce column $j$ of the identity matrix.
Keep the orientation correct: these system solutions are placed in columns, not rows. The equation $AA^{-1}=I$ checks all columns at once.
Gaussian elimination for all right-hand sides at once
Write the augmented matrix $[A\mid I]$. Apply row operations to the entire row, including the right-hand side. The goal is to turn the left half into $I$, not merely into a triangular matrix. The right half will then be $A^{-1}$.
Why does this work? Each operation transforms the systems into equivalent ones, simultaneously for all right-hand sides. Once the coefficients on the left form the identity, the right side contains the system solutions: exactly the required inverse columns.
Consider the small example $A=\begin{pmatrix}2&1\\1&1\end{pmatrix}$. First swap the rows to obtain a leading one.
$$\left[\begin{array}{cc|cc}2&1&1&0\\1&1&0&1\end{array}\right]\ \longrightarrow\ \left[\begin{array}{cc|cc}1&1&0&1\\2&1&1&0\end{array}\right].$$Now apply $R_2\leftarrow R_2-2R_1$, then $R_2\leftarrow-R_2$, then $R_1\leftarrow R_1-R_2$. The result is
$$\left[\begin{array}{cc|cc}1&0&1&-1\\0&1&-1&2\end{array}\right],\qquad A^{-1}=\begin{pmatrix}1&-1\\-1&2\end{pmatrix}.$$The inverse trace here is $1+2=3$. It is not $1/\tr A$: the reciprocal of a sum is not the sum of the inverse matrix's diagonal. Check by multiplication: the first product row is $(2-1,-2+2)=(1,0)$, and the second is $(1-1,-1+2)=(0,1)$.
For order $3$, the algorithm is the same: successively obtain leading ones in all three columns and clear the entries above and below them. If a pivot is zero, look for a nonzero entry below and swap rows. If none exists, check singularity; never divide by zero.
An elementary check for an outer-product update
We can write the matrix action without listing every entry: $(I+uv^T)x=x+u(v^Tx)$. The bracketed term $v^Tx$ is a scalar. This shows that the added vector always points along $u$.
This helps check a computed inverse column by column: verify $z_j+u(v^Tz_j)=e_j$ for each column $z_j$. No new inverse formula is needed.
An optional shortcut after mastering elimination
For a square identity update, $\det(I+uv^T)=1+v^Tu$. This is a special case of the matrix determinant lemma. Here the conditions are that $u,v$ are columns of the same length and the base matrix is exactly $I$.
Let $c=v^Tu$. If $1+c\ne0$, direct multiplication verifies
$$ (I+uv^T)^{-1}=I-\frac{uv^T}{1+c}. $$Expanding the product uses $(uv^T)(uv^T)=u(v^Tu)v^T=cuv^T$. The coefficient of the update becomes $1-1/(1+c)-c/(1+c)=0$. This special case of the Sherman–Morrison formula is thus verified by ordinary multiplication.
If $1+c=0$, the formula is undefined and no inverse exists: $(I+uv^T)u=(1+c)u=0$, with $u\ne0$. Do not try to cancel the zero denominator. Memorizing the names is unnecessary; every mandatory problem can be solved by Gaussian elimination.
Keep the norm skill active
The vector task Q7 uses a different operation: expand the squared length as the sum dotted with itself.
$$\|au+bv\|^2=a^2\|u\|^2+b^2\|v\|^2+2ab\|u\|\|v\|\cos\varphi.$$The cross term retains the sign of $ab\cos\varphi$. After calculation, take the nonnegative square root. An angle of $120$ degrees has negative cosine; this does not change the sign of the entire squared norm.
Finally, the length must lie between $\big||a|\|u\|-|b|\|v\|\big|$ and $|a|\|u\|+|b|\|v\|$. If it does not, check the cross term and the final square root.