Convert MATLAB code to R

42,721

Solution 1

Paul Gilbert provides a rough Bash script that could get you started (he claims it will convert about 80% of the way) on the R mailing list:

#!/bin/csh
cp $1 $2
ex -s $2 <<eof
   g/%/s//#/g
   g/function\(..*\)=\(..*\)(\(..*\)/s//\2 <-function( \3 { \1/
   g/end/s//   } #/
   g/for\(..*\)=\(..*\):\(..*\)/s//for ( \1 in \2 : \3 ) {/
   g/_/s//./g
   g/;/s///g
   g/==/s//@@/g
   g/=/s//<-/g
   g/@@/s//==/g
   g/zeros(/s//matrix(0,/g
   g/ones(/s//matrix(1,/g
   g/eye(/s//diag(1,/g
   g/\/s//solve(,)/g
   g/fsolve('\(..*\)'/s//ms(~\1 /g
   g/param(\(..*\))/s//param[ \1 ] /g
   g/var(\(..*\))/s//var[ \1 ] /g
   g/mod1(\(..*\)/s//mod1[ \1 /g
   wq
eof

Solution 2

No there is no easy conversion. Some will translate nearly exactly, some will translate only with great pain and suffering. At least you'll be using R though! Start here to work out analogous functions and syntax:

http://cran.r-project.org/doc/contrib/R-and-octave.txt

http://cran.r-project.org/doc/contrib/Hiebeler-matlabR.pdf

When you get stuck please ask specific questions here. This is really too vague as it stands, though those reference cards will help with getting started.

Solution 3

An alternative to translating the code would be to call MATLAB from within R, using the RMatlab package.

I have not tried RMatlab, but the package description states:

This package provides methods to read and write MAT files. It also makes it possible to communicate (evaluate code, send and retrieve objects etc.) with Matlab v6 or higher running locally or on a remote host.

Solution 4

Please see the comments on this issue: URL:https://mandymejia.wordpress.com/2014/08/18/three-ways-to-use-matlab-from-r/

She mentions several options:

Option 1: Run a single MATLAB command at a time using system()

Option 2: Use R.matlab to send code to the MATLAB server

Option 3: Write an entire MATLAB program using writeLines() and run using system()

Share:
42,721

Related videos on Youtube

user236215
Author by

user236215

Updated on July 09, 2022

Comments

  • user236215
    user236215 almost 2 years

    Is there a tool for converting MATLAB code to R?

    I have a lot of code that needs to be converted from MATLAB to R. It doesn't have to be accurate, but it will be helpful in giving a head start.

  • Iterator
    Iterator over 12 years
  • David LeBauer
    David LeBauer over 12 years
    @user236215 both R and RMatlab run on windows.
  • Geek On Acid
    Geek On Acid over 12 years
    I think that R.Matlab package will read Matlab .mat files, which are basically data files, but it won't help you with translating code from .m files.
  • David LeBauer
    David LeBauer over 12 years
    @GeekOnAcid you are correct, but it provides an interface to MATLAB, so that MATLAB can evaluate the code.
  • runlevel0
    runlevel0 about 9 years
    The correct name is R.matlab, this is de rcran URL: cran.r-project.org/web/packages/R.matlab/index.html

Related