## Sunday, July 5, 2009

### Calling R from within Matlab

The COM interface allows Matlab users to call R from within Matlab. It is quite convenient for matlab users to interact with R functions. To make R project available to your matlab is very simple.

TO DO LIST:
1. Install Matlab: http://www.mathworks.com/
2. Install R: Open http://www.r-project.org/ , choose download R and then select a mirror.
3. Install the R package "rscproxy" in R. The package is available at: http://cran.r-project.org/. Go to package and find rscproxy. This can also be simply done by typing "install.packages('rscproxy') in R prompt. Then choose a mirror. Wait for 2 seconds and it is done.
7. You can enjoy the convenience of having Matlab to call R now. Test if it is working by type "Rdemo" in Matlab commond window. If you are interested in nonparametric denstiy estimation, run the following MatlabcallRnp.m file

function MatlabcallRnp()
%% MatlabcallRnp() illustrates how to use Matlab to call the %% NP package in R. %% Note: all .m files in the Matlab_RLINK folder should be %% copied into the current directory in Matlab. You do not %% need run R when it is called.% Author Infor.% Yundong Tu% Department of Economics,% Univeristy of California, Riverside% e-mail: yundong.tu@email.ucr.edu
%% Connect to an R SessionopenR
%% Push data into R with putRdata()a = randn(200,1);putRdata('a',a)%%{%% Call the density (R function to estimate density) %% command into Matlab with evalR() %get the evaluation points for the density estimator xx= evalR('density(a)\$x'); %get the corresponding evaluation of density fx= evalR('density(a)\$y'); %figure subplot(2,1,1) plot(xx,fx); %plot the density function% %the density plot can be also called by R as evalR('plot(density(a),mfrow=c(2,1))');%}
%% Call the npudens (R function to estimate density) %% command into Matlab with evalR() %get the evaluation points for the density estimator evalR('data=data.frame(a)'); evalR('library(np)')
evalR('xx=npudens(data)\$eval'); %dataframe xx=evalR('xx[[1]]') %matrix %get the corresponding evaluation of density fx= evalR('npudens(data)\$dens') %figure %xy=eda; [xx,ind]=sort(xx); fx=fx(ind); subplot(2,1,2) plot(xx,fx); %plot the density function %the npudens plot can be also called by R as evalR('plot(npudens(a),add=FALSE)');%}%%{%% Run a series of commands and grab %% the result using getRdata()%save time to call density() just once, also get the bandwidthevalR('den=density(a)'); xx=evalR('den\$x'); % the same as: evalR('xx=den\$x'); xx=getRdata('xx');fx=evalR('den\$y'); bw=evalR('den\$bw');
figureplot(xx,fx);hold ontitle({['R-output DENSITY'];['Bandwidth=',num2str(bw)]});hold off%}%% Close the connectioncloseR

http://www.cs.ubc.ca/~murphyk/Software/callingRfromMatlab.html