All possible solutions of a system of equations in R

1

I have the following system of equations:

x+y+z=20
z-y>0
y-x>0

I would like to know if there is any way in R to list all possible solutions for x, y, z and be able to save them in a matrix (3, m), where m represents the number of possible solutions.

    
asked by Oscar Palomino 22.11.2017 в 13:57
source

1 answer

0

All possible solutions would tell you that you can not, but yes, you can calculate some of these solutions by putting together a combination of values and testing the restrictions, for example:

# Creamos una función para validar las restricciones
fnvalid <- function(x) {
    # x+y+z=20
    # z-y>0
    # y-x>0
    if (x[1]+x[2]+x[3] == 20 &
        -x[2]+x[3] > 0 &
        -x[1]+x[2] > 0) {
        return(TRUE)
    }
    return(FALSE)
}

Then we generate a matrix of 3xN with combinations of integer values for each variable, the size is to the taste of the consumer.

m <- as.matrix(expand.grid(lapply(numeric(3), function(x) c(-10:10))))

In this example we generate all combinations of integers between -10 and 10 for the three variables. Finally we apply the function per row to validate the restrictions and we obtain the values that meet all the conditions:

m[which(apply(m, MARGIN=1, fnvalid)),]

In this example, the result would be:

     Var1 Var2 Var3
[1,]    5    7    8
[2,]    5    6    9
[3,]    4    7    9
[4,]    3    8    9
[5,]    4    6   10
[6,]    3    7   10
[7,]    2    8   10
[8,]    1    9   10
    
answered by 22.11.2017 в 16:27