---
# System prepended metadata

title: 線性代數常用R語言指令整理
tags: [線代, 程式]

---

# 線性代數常用R語言指令整理
###### tags: `線代`
---
## 基本指令
``` r
# 向量
vector1 <- c(1,2,3)

# 連續值快速表示
vector2 <- c(1:16)

# print指令只能生出字串，加入向量可快速命名
print(cat("A",c(1,2)))

# 看output需直接打變數名稱
vector1
```

## 建立矩陣

``` r
# 注意因為向量是橫的，所以是一列列輸入
A <- matrix(c(1,2,3,4,6,8,10,66), nrow =2 , ncol = 4)
```
>output:
![](https://hackmd.io/_uploads/B13NcqJIh.png)


不輸入參數列行參數的話，預設為動行。

``` r
# 4為4行的意思
 A <- matrix(c(1,2,3,4,6,8,10,66), 4)
 print(A)
```
>output:
![](https://hackmd.io/_uploads/rJHNj5kI2.png)

### 建立對角 or $I$
```r
# 一般對角矩陣
dia <- diag(c(5,9,11))

# 單位矩陣I
i <- diag(c(1,1,1))
```
>output:
![](https://hackmd.io/_uploads/HJAOms1In.png)
![](https://hackmd.io/_uploads/Bkmomi1Un.png)

## 矩陣乘法

``` r
A <- matrix(c(1,6,9,5,4,10,81,3,8,45,66,79),4)
B <- matrix(c(1:6),3)
# 乘法
A %*% B
```
>output
![](https://hackmd.io/_uploads/HJfD-sy8n.png)


## 轉置矩陣
```r
# 原本的B是3×2的矩陣
t(B)
```
>output
![](https://hackmd.io/_uploads/ry5wToyLn.png)


## 內積
- **條件: 長度一樣、單列or行向量。**
- 向量也OK。
``` r
B <- matrix(c(0:4),5)
A <- matrix(c(2,4,6,8,10),5)
A*B
```
>ouput:
![](https://hackmd.io/_uploads/S1caR5kIh.png)

## 反矩陣
- 條件:須為方陣
```r
# 偷懶拿前面的對角矩陣來用
solve(dia)
```
>ouput:
![](https://hackmd.io/_uploads/B1-d4sJLn.png)

## 行列式
- 條件:須為方陣
```r
# 加矩陣名稱即可
det(dia)
```

## 特徵值及特徵向量
- 條件:需為方陣
```r
# 特徵值+特徵向量
A <- matrix(c(1,3,5,-3,9,-5,10,-1,6),3)
eigen(A)
```
>output:
***第一個是特徵值，第二個是特徵向量***
![](https://hackmd.io/_uploads/rJVG_jy8n.png)

## 正交


## LU分解
$A=LU$
L為正交矩陣、U為下三角矩陣
- 前置作業:需要套件Matrix
``` r
# 安裝(已安裝不用跑這條程式)
install.packages("Matrix")
# 載入套件
library(Matrix)

# 不確定是啥東東:(
lu <- lu(A)

# 真正的output
lue <- expand(lu)
```
>output
![](https://hackmd.io/_uploads/BybkhoyU2.png)

# code
## 正交投影公式解
$P=X(X^TX)^{-1}Z$
向量關係圖
![未命名](https://hackmd.io/_uploads/SJunj27Ka.png)

``` r
X <- matrix(c(3,0,-1,1,5,3),nrow =3 , ncol = 2)
Z <-  c(1,2,3)
cat("X", "\n")
print(X)
cat("Z", "\n")
print(Z)

X_t <- t(X)
cat("x transpose","\n")
print( X_t)

cat("x transpose times x","\n")
print(X_t %*% X)
X1 <- solve(X_t %*% X)
cat("x^T times x inverse","\n")
print( X1)

# last squares solution
ls <- X1 %*% X_t %*% Z
cat("last squares solution","\n")
print(ls)

P <- X  %*% X1  %*% X_t
cat("orthogonal matrix","\n")
print( P)

result <- X  %*% X1  %*% X_t %*% Z

cat("projection of z","\n")
print(result)
```

## G-S Procresess 嘗試
前提: 須為方陣
``` r
X <- matrix(c(3,0,-1,1,5,3),nrow =3 , ncol = 2)
Z <-  c(1,2,3)

# QR分解
QR <- qr(X)
# 取Q
Q <- qr.Q(GS)

```




# see also
**統計常用指令整理**
[https://hackmd.io/DcMsUqUYQ3mywdkS4WFv8Q](https://hackmd.io/DcMsUqUYQ3mywdkS4WFv8Q)


