From affdab66cb720db66bbf05e8f8d9c8d7b6e3d542 Mon Sep 17 00:00:00 2001 From: noah Date: Mon, 27 Mar 2023 10:23:47 -0500 Subject: [PATCH] solve polynomial with points via matrix --- Schrick-Noah_Homework-5.R | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/Schrick-Noah_Homework-5.R b/Schrick-Noah_Homework-5.R index 5653495..bd590fa 100644 --- a/Schrick-Noah_Homework-5.R +++ b/Schrick-Noah_Homework-5.R @@ -12,16 +12,41 @@ x <- solve(A,b) x # b. Verify with matrix mult -A%*%x == b +all.equal(b, as.matrix(A %*% x)) ## 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 +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 +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 +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 # a. Create vectors