Matlabfunction() similar to MATLAB in R

Asked

Viewed 144 times

2

There is a function similar to matlabFunction() MATLAB? Or how to do this in R?

The function in MATLAB.

syms x
dados = inputdlg({'P(x): ', 'Q(x): ', 'R(x): ', 'N: '},'Dados');
P = matlabFunction(sym(dados{1}),'vars',x,'file','px');

In R I’m trying to do it this way:

P <- function(x){
   expr = dados[1]
   y <- eval(parse(text= expr), list(x))
   return (y)
} 

But I still have to change the expression within the function or pass it by parameter.

  • 2

    What this function does in Matlab?

  • Converts symbolic expression to a function.

2 answers

2


In Matlab the function inline is equivalent to function matlabFunction() and in R the command function can be used to create the same features.

Using both functions in Matlab to prove similarity:

f1 = inline('sin(x/3) - cos(x/5)')

f1 =

     Inline function:
     f1(x) = sin(x/3) - cos(x/5)

f2 = matlabFunction(sin(x/3) - cos(x/5))

f2 = 

    @(x)-cos(x.*(1.0./5.0))+sin(x.*(1.0./3.0))

Calling f1 and f2 to compute and prove that sine(2/3) - cosine(2/5) is equal to -0.3027 in any of the functions:

f1(2)

ans =

   -0.3027

f2(2)

ans =

   -0.3027

Now the same function created similarly in R:

f <- function(x) sin(x/3) - cos(x/5)
f(2) 
-0.3026912 

1

I solved the problem as follows:

make.Rfunction <- function(expressao) {
    fn <- function(x) {
        return(eval(parse(text= expressao), list(x)))
    }
return(fn)
}

dados <- c("x+2")
P <- make.Rfunction(dados[1])
P(2) # resposta : [1] 4
P(3) # resposta : [1] 5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.