當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 solve()用法及代碼示例


R語言中的solve()函數用於求解線性代數方程。這裏的方程類似於 a*x = b,其中 b 是向量或矩陣,x 是將要計算其值的變量。

用法: solve(a, b)

參數:
a:方程的係數
b:方程的向量或矩陣

範例1:


# R program to illustrate
# solve function
  
# Calling solve() function to
# calculate value of x in
# ax = b, where a and b is 
# taken as the arguments
solve(5, 10)
solve(2, 6)
solve(3, 12)

輸出:

[1] 2
[1] 3
[1] 4

範例2:


# R program to illustrate
# solve function
  
# Create 3 different vectors 
# using combine method. 
a1 <- c(3, 2, 5) 
a2 <- c(2, 3, 2) 
a3 <- c(5, 2, 4) 
    
# bind the three vectors into a matrix  
# using rbind() which is basically 
# row-wise binding
A <- rbind(a1, a2, a3) 
    
# print the original matrix 
print(A) 
    
# Use the solve() function  
# to calculate the inverse
T1 <- solve(A) 
    
# print the inverse of the matrix
print(T1) 

輸出:

   [, 1] [, 2] [, 3]
a1    3    2    5
a2    2    3    2
a3    5    2    4
              a1          a2         a3
[1, ] -0.29629630 -0.07407407  0.4074074
[2, ] -0.07407407  0.48148148 -0.1481481
[3, ]  0.40740741 -0.14814815 -0.1851852



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Solve Linear Algebraic Equation in R Programming – solve() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。