Function for translating linear equations into matrix form in R?

I was wondering if there are any packages or other ready-made solutions for R that can translate sets of linear equations into matrix form (for example, for solving through the Gauss-Seidel Algorithm ), similarly to the equationsToMatrix(eqns,vars)

+5
source share
2 answers

1) This is not quite what you are asking for, but maybe it will still help:

 library(Ryacas) x <- Sym("x") y <- Sym("y") Simplify(Solve(List(x - y == 0, x + 2*y == 3), List(x, y))) 

giving:

 expression(list(list(x - y == 0, y - 1 == 0))) 

2) If we know that these are linear equations exactly in the form indicated in the question, try this. Two strapply calls match the regular expression with the args components, capture the lines matching the parts of the regular expressions in parentheses, and call the function specified as the third argument, with these captured lines as arguments. We combine the strapply outputs with rbind.fill and replace any NA that it generates with zero.

 library(gsubfn) # strapply library(plyr) # rbind.fill eqn <- function(...) { args <- c(...) x2num <- function(x, y) { # determine coefficient value as a numeric z <- gsub(" ", "", x) setNames(if (z == "-") -1 else if (z == "") 1 else as.numeric(z), y) } lhs <- strapply(args, "(-? *\\d*)[ *]*([az])", x2num) lhs <- do.call(rbind.fill, lapply(lhs, function(x) as.data.frame(t(x)))) lhs <- as.matrix(lhs) lhs[] <- ifelse(is.na(lhs), 0, lhs) list(lhs = lhs, rhs = strapply(args, "== *(\\d)", as.numeric, simplify = TRUE)) } # test it out eqn("x - y == 0", "2*y == 3") 

giving:

 $lhs xy [1,] 1 -1 [2,] 0 2 $rhs [1] 0 3 

Update: Generalized so that now not all variables should be in each equation, and variables can be in different orders in different equations.

+4
source

It is impossible to tell from your example whether you want a simple solution to linear equations or a more general system solver. If the latter, check out the BB and nleqslv .

You may also be interested in the wrapper tool, written by some seriously distorted mind :-), in the ktsolve package. This last tool allows you to establish an arbitrary system of equations and return to the solution for any desired set of variables.

+2
source

Source: https://habr.com/ru/post/1207471/


All Articles