mldivide: Matlab backslash operator

Description Usage Arguments Details Value Note Examples

View source: R/mldivide.R

Description

Emulate the Matlab backslash operator “\” through QR decomposition.

Usage

1
2
mldivide(A, B, pinv = TRUE)
mrdivide(A, B, pinv = TRUE)

Arguments

A, B

Numerical or complex matrices; A and B must have the same number of rows (for mldivide) or the same number of columns (for mrdivide)

pinv

logical; shall SVD decomposition be used; default true.

Details

mldivide performs matrix left division (and mrdivide matrix right division). If A is scalar it performs element-wise division.

If A is square, mldivide is roughly the same as inv(A) %*% B except it is computed in a different way — using QR decomposition.

If pinv = TRUE, the default, the SVD will be used as pinv(t(A)%*%A)%*%t(A)%*%B to generate results similar to Matlab. Otherwise, qr.solve will be used.

If A is not square, x <- mldivide(A, b) returnes a least-squares solution that minimizes the length of the vector A %*% x - b (which is equivalent to norm(A %*% x - b, "F").

Value

If A is an n-by-p matrix and B n-by-q, then the result of mldivide(A, B) is a p-by-q matrix (mldivide).

Note

mldivide(A, B) corresponds to A\B in Matlab notation.

Examples

1
2
3
4
5
6
7
8
# Solve a system of linear equations
A <- matrix(c(8,1,6, 3,5,7, 4,9,2), nrow = 3, ncol = 3, byrow = TRUE)
b <- c(1, 1, 1)
mldivide(A, b)  # 0.06666667 0.06666667 0.06666667

A <- rbind(1:3, 4:6)
mldivide(A, c(1,1))                 # -0.5  0  0.5 ,i.e. Matlab/Octave result
mldivide(A, c(1,1), pinv = FALSE)   # -1    1  0         R    qr.solve result

Example output

           [,1]
[1,] 0.06666667
[2,] 0.06666667
[3,] 0.06666667
              [,1]
[1,] -5.000000e-01
[2,]  3.025358e-15
[3,]  5.000000e-01
     [,1]
[1,]   -1
[2,]    1
[3,]    0

pracma documentation built on Dec. 11, 2021, 9:57 a.m.