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.



  • 1
    $\begingroup$ If the function is not computational intense, maybe you could use CloudDeploy to create a web API. $\endgroup$ 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')

    fullURL = ['https://www.wolframcloud.com/objects/alphanumericsequence'...

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

BTW, I kept getting a network connection error in Matlab when I used the original "https" protocol in the URL, so I switched to "http" protocol in the m-file URL (as this is public anyway and doesn't require any logins).

  • $\begingroup$ That's great - I will try this later. Many thanks. Just wondering - is there any way this could be called from R? Best, Ben $\endgroup$
    – ben18785
    May 14 '16 at 14:53
  • 1
    $\begingroup$ @ben18785, I don't use R much but you should be able to use either scan or read commands to get data in from a URL. Maybe this stackoverflow question will help. $\endgroup$
    – Rashid
    May 14 '16 at 15:14
  • $\begingroup$ Thanks Rashid, much appreciated. Best, Ben $\endgroup$
    – ben18785
    May 14 '16 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.