# Create a Mathematica function that can be called from R or Matlab

I would like to export a function from Mathematica to allow it to be accessed from R and/or Matlab.

Is there a way to do this?

As an example, suppose I want to export the following (albeit contrived) function, that could be hard to replicate in R:

f[x_Integer] := Prime[x]


The actual function is long-winded, and its details don't matter (I think, but let me know if you need these). Basically I want to avoid trying to code up something that took me ages in Mathematica, into R or Matlab.

The reason I want to do this is I am writing a class problem set, and I want students (using Matlab or R) to be able to call a function that I have created in Mathematica.

Best,

Ben

• If the function is not computational intense, maybe you could use CloudDeploy to create a web API. – xslittlegrass May 14 '16 at 2:32

As @xslittlegrass suggested in the comments, you could use CloudDeploy[].

The APIFunction[] makes it easy to accept input parameters and return the evaluation results of a function. Then you could use urlread() in Matlab to query/read answers. Here is an example for the Prime[x] case.

First in Mathematica (adapted from the APIFunction documentation):

func = APIFunction[{"x" -> "Integer"}, Prime[#x] &];
api = CloudDeploy[func, Permissions -> "Public"]


This will return a CloudObject with a URL that looks like "https://www.wolframcloud.com/objects/alphanumericsequence"

Then we can define a m-file function in Matlab:

 function [out]=primeAPI(x)
if ~isnumeric(x) || mod(x,1)~=0
error('input must be an integer')
end

fullURL = ['https://www.wolframcloud.com/objects/alphanumericsequence'...
,'?x=',num2str(x)];

Running, primeAPI(100) from the Matlab command line then returns the number 541