# qrinsert

Insert column or row into QR factorization

## Syntax

```[Q1,R1] = qrinsert(Q,R,j,x) [Q1,R1] = qrinsert(Q,R,j,x,"col") [Q1,R1] = qrinsert(Q,R,j,x,"row") ```

## Description

`[Q1,R1] = qrinsert(Q,R,j,x)` returns the QR factorization of the matrix `A1`, where `A1` is `A = Q*R` with the column `x` inserted before `A(:,j)`. If `A` has `n` columns and `j = n+1`, then `x` is inserted after the last column of `A`. If `A` and `x` have different data types, then `Q1` and `R1` have the same data type as `A`.

`[Q1,R1] = qrinsert(Q,R,j,x,"col")` is equivalent to `[Q1,R1] = qrinsert(Q,R,j,x)`.

`[Q1,R1] = qrinsert(Q,R,j,x,"row")` returns the QR factorization of the matrix `A1`, where `A1` is `A = Q*R` with an extra row, `x`, inserted before `A(j,:)`.

## Examples

Given the QR factorization of a `5-by-5` matrix, return the QR factorization of that matrix with a row inserted into it, using one function call to `qrinsert`.

```A = magic(5); [Q,R] = qr(A); j = 3; x = 1:5; [Q1,R1] = qrinsert(Q,R,j,x,"row") Q1 = 0.5231 0.5039 -0.6750 0.1205 0.0411 0.0225 0.7078 -0.6966 0.0190 -0.0788 0.0833 -0.0150 0.0308 0.0592 0.0656 0.1169 0.1527 -0.9769 0.1231 0.1363 0.3542 0.6222 0.6398 0.2104 0.3077 0.1902 0.4100 0.4161 -0.7264 -0.0150 0.3385 0.4500 0.4961 -0.6366 0.1761 0.0225 R1 = 32.4962 26.6801 21.4795 23.8182 26.0031 0 19.9292 12.4403 2.1340 4.3271 0 0 24.4514 11.8132 3.9931 0 0 0 20.2382 10.3392 0 0 0 0 16.1948 0 0 0 0 0```

The `qrinsert` function returns a valid QR factorization. However, the factorization results may vary if you explicitly insert the row into the original matrix and then calculate its QR factorization using a function call to `qr`.

```A2 = [A(1:j-1,:); x; A(j:end,:)]; [Q2,R2] = qr(A2) Q2 = -0.5231 0.5039 0.6750 -0.1205 0.0411 0.0225 -0.7078 -0.6966 -0.0190 0.0788 0.0833 -0.0150 -0.0308 0.0592 -0.0656 -0.1169 0.1527 -0.9769 -0.1231 0.1363 -0.3542 -0.6222 0.6398 0.2104 -0.3077 0.1902 -0.4100 -0.4161 -0.7264 -0.0150 -0.3385 0.4500 -0.4961 0.6366 0.1761 0.0225 R2 = -32.4962 -26.6801 -21.4795 -23.8182 -26.0031 0 19.9292 12.4403 2.1340 4.3271 0 0 -24.4514 -11.8132 -3.9931 0 0 0 -20.2382 -10.3392 0 0 0 0 16.1948 0 0 0 0 0```

## Algorithms

The `qrinsert` function inserts the values of `x` into the `j`th column (or row) of `R`. It then uses a series of Givens rotations to change the nonzero elements of `R` on and below the diagonal in the `j`th column (or row) to zero. 

 Golub, Gene H., and Charles F. Van Loan. Matrix Computations. 4th ed. Baltimore, MD: Johns Hopkins University Press, 2013, Sections 6.5.2–6.5.3, pp. 335–338.