How to call MATLAB commands from JavaScript with pythonia

How can I call MATLAB commands from my JavaScript code?

 Accepted Answer

This example demonstrates how to call MATLAB commands from JavaScript using Python, MATLAB’s Python Engine, and the pythonia package, which is a bridge to call and interop Python APIs from Node.js.
The
contains the following files that are the main components needed to reconstruct the folder structure and run the example.
(a)  README.txt: Contains the instructions in this article
(b)  hello.js: Node.js JavaScript that uses the Pythonia to call Python code.
import { python } from 'pythonia'
const time = await python('./time.py')
console.log("It's", await time.what_time_is_it())
console.log("The sqrt of 4.0 is: ", await time.try_matlab_sqrt(4.0))
python.exit()
(c)   time.py: Python code that uses MATLAB’s Python Engine.
import datetime
def what_time_is_it():
return str(datetime.datetime.now())
def try_matlab_sqrt(data):
import matlab.engine
eng = matlab.engine.start_matlab("-nojvm")
return eng.sqrt(float(data))
The instructions for installing and running this example are as follows.
1) Install MATLAB Engine for Python
2) Download and install Node.js and the npm package manager
https://nodejs.org/en/download/
3) Create a project folder (e.g., pythoniaExample) and copy hello.js and time.py to the new directory.
C:\Users\username> mkdir pythoniaExample
4) Set up an npm package and edit the package.json file.
In a terminal from the project folder, set up a new npm package using the following command and selecting the default options.
C:\Users\username\pythoniaExample> npm init
The above command will create a new package.json file. Edit this file to include the following line: "type": "module". Here is an example of the package.json file.
{
"name": "pythoniaExample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
6) Install pythonia
C:\Users\username\pythoniaExample> npm i pythonia
6) (May be required) Set PYTHON_BIN value. For example, the path to the Python executable is C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe, then use the following command.
C:\Users\username\pythoniaExample> set PYTHON_BIN=C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe
7) Run test code
C:\Users\usernme\pythoniaExample> node hello.js
The output will look something like this.
It's 2022-09-27 07:46:11.156392
The sqrt of 4.0 is: 2

More Answers (0)

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!