9

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

ben18785
  • 3,167
  • 15
  • 28

1 Answers1

9

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)];
    apiResponse=urlread(fullURL);
    out=str2num(apiResponse);

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).

Rashid
  • 1,523
  • 10
  • 18