solve polynomial with points via matrix
This commit is contained in:
parent
a256f38a50
commit
affdab66cb
@ -12,16 +12,41 @@ x <- solve(A,b)
|
|||||||
x
|
x
|
||||||
|
|
||||||
# b. Verify with matrix mult
|
# b. Verify with matrix mult
|
||||||
A%*%x == b
|
all.equal(b, as.matrix(A %*% x))
|
||||||
|
|
||||||
## 2. Matrix from polynomial
|
## 2. Matrix from polynomial
|
||||||
# a. Create vector for x and y
|
# a. Create vectors for x and y
|
||||||
|
xvec <- c(-3,-1.5,0.5,2,5)
|
||||||
|
yvec <- c(6.8,15.2,14.5,-21.2,10)
|
||||||
|
|
||||||
# b. Create coefficient matrix
|
# b. Create coefficient matrix
|
||||||
|
A.2 <- matrix(ncol=length(xvec), nrow=length(xvec))
|
||||||
|
for (i in 1:length(xvec)){
|
||||||
|
A.2[,i] = xvec^(i-1)
|
||||||
|
}
|
||||||
|
A.2
|
||||||
|
|
||||||
# c. Solve
|
# c. Solve
|
||||||
|
if (!require("matlib")) install.packages("matlib")
|
||||||
|
library(matlib)
|
||||||
|
|
||||||
|
# verify
|
||||||
|
bvec <- solve(A.2, yvec)
|
||||||
|
all.equal(as.matrix(yvec), A.2 %*% bvec) # use all.equal instead of == (tols and storage type)
|
||||||
|
# EX: identical(as.double(8), as.integer(8)) returns FALSE
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# d. Plot
|
# d. Plot
|
||||||
|
poly_predict <- function(x){
|
||||||
|
# given input x, returns polynomial prediction
|
||||||
|
sum(bvec*c(1,x,x^2,x^3,x^4))
|
||||||
|
}
|
||||||
|
|
||||||
|
xdomain <- seq(min(xvec),max(xvec),.2) # predicted domain
|
||||||
|
y.predict <- sapply(xdomain,poly_predict) # predicted range
|
||||||
|
plot(xvec,yvec,ylim=c(-50,20)) # plot data
|
||||||
|
lines(xdomain,y.predict,type="l") # overlay solid line
|
||||||
|
|
||||||
## 3. Kirchoff
|
## 3. Kirchoff
|
||||||
# a. Create vectors
|
# a. Create vectors
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user