Description
MatlabJS is a lightweight and easy-to-use library with essential functions for Matlab® / GNU Octave users who are new to Javascript. It is meant for rapid prototyping of projects or code conversion from Matlab/Octave. This free and open source utility is currently at versionloading..
.
Examples:
The library is already loaded in this webpage.To try it out, open the browser console using
rightclick
+ inspect
and test these lines of code:
tic()
a=linspace(0,1)
disp(a)
b=eye(8)
c=rand(8)
d=mul(b,c)
toc()
How to use this in your project:
Method 1 - CDN (recommended - to get the latest updates and bug fixes):
Include the following script tag within your html head. <script src="https://cdn.jsdelivr.net/gh/VivekTRamamoorthy/MatlabJS/Matlab.js"></script>
This would only give the standard functions. To use plotting tools, additionally include plotlib.js file.
<script src="https://cdn.jsdelivr.net/gh/VivekTRamamoorthy/MatlabJS/plotlib.js"></script>
Method 2 - File inclusion (robust - to include a non-breaking local version):
DownloadMatlab.js
file from the MatlabJS repository to your project and
and include it using a script tag as below.
<script src="Matlab.js"></script>
Method 3 - Using NodeJS:
MatlabJS is also available as an npm package. To use this method, it is presumed that Node is installed on your machine. If not, do this first. Use the following command from a terminal within your project folder.
npm install matlabjs
Use const MatlabJS = require("matlabjs")
to include the namespace in your js modules.Then use the functions like below:
let A = MatlabJS.linspace(0,1)
Limitations:
c=A*b
for matrices and arrays.
Instead we have to resort to using universal functions c=mul(A,b)
that perform actions based on the input datatypes.
Full list of functions:
Use left or right arrow keys to scroll if the the table is not fully visible.Matlab function | MatlabJS equivalent | Example usage | Description |
---|---|---|---|
tic | tic() | Starts recording time | |
toc | toc() | tic(); t=toc(); |
Prints elapsed time since start |
clc | clc() | clc() | Clears console |
linspace | linspace | A=linspace(0,1) // [0 .1010.. 1] B=linspace(10,20,3) // [10,15,20] |
Produces linearly spaced array. |
logspace | logspace | A=logspace(1,1000,4) // [1 10 100 1000] B=logspace(1,25,3) // [1,5,25] |
Produces logarithmically spaced arrays. |
disp, display | disp, display | A=linspace(0,1) B=linspace(10,20,3) disp(A) display(B) |
Displays matrices and arrays in console |
isfield | isfield(struc,fieldname) |
struc={x:10,y:100} isfield(struc,'x') // true isfield(struc,'a') // false |
Checks the presence of fieldnames in a structure |
size | size(A) |
A=[[1,2,3],[3,4,5]] size(A) // [2,3] |
Dimensions of a matrix or array |
length | A.length length(A) |
A=[1,2,3,3,4,5] A.length // 6 length(A) // 6 |
Length of an array |
find | find |
A=[1,2,0,0,4,5] find(A) // [1, 2, 5, 6] |
Find nonzero elements |
sort | sort() | A=[3,2,1,5,7]; [sortedA,indices]=sort(A); disp(sortedA); // [1,2,3,5,7] disp(indices); // [3,2,1,4,5] |
Sorts numbers ascending |
sum | sum | A=[1,2,3] sum(A) // 6 B=[[1,2,3],[4,5,6],[7,8,9]] disp(sum(B,1)) // column sum [12,15,18] disp(sum(B,2)) // row sum [[6],[15],[24]] |
Sum of an array Column sum of a matrix Row sum of a matrix |
abs | abs | A=[1,-2,3] abs(A) // [1,2,3] B=[[1,-2,3],[-4,5,6],[-7,8,-9]] disp(abs(B)) //[1,2,3],[4,5,6],[7,8,9] |
Absolute value of num, array or matrix |
sqrt | sqrt | A=[1,4,2] disp(sqrt(A)) // [1,2,1.414] A=rand(4) disp(A) disp(sqrt(A)) |
Square root of num, array or matrix |
setdiff | setdiff | A=[4,3,1,5] B=[5,3,7,8] setdiff(A,B) // [1,4] |
Set difference (sorted) |
min | min | A=[1,3,-5,9] disp(min(A)) // -5 B=[[1,2,3],[4,5,6],[7,8,9]] disp(B) disp(min(B,1)) // elemwise min disp(min(B,4)) // disp(min(B,[],1)) // column min disp(min(B,[],2)) // row min |
Minimum of array or matrix |
max | max | Similar to min | Maximum of an array or matrix |
a:b:c | range(a,b,c) | range(2,0.5,4) // [2,2.5,3,3.5,4] |
Array from a to c in steps of b |
triu | triu(Matrix,k) | disp(triu(rand(4))) disp(triu(rand(4),1)) |
Upper trianular matrix |
[A, B] | concatRows(A,B) | A=ones(3,3) disp(A) B=rand(3,3) disp(B) C=concatRows(A,B) disp(C) // 3 x 6 matrix |
Concatenate rows of two matrices |
[A; B] | concatCols(A,B) | A=ones(3,3) disp(A) B=rand(3,3) disp(B) C=concatCols(A,B) disp(C) // 6 x 3 matrix |
Concatenate columns of two matrices |
A' | transpose(A) | A=[[1,2,3],[4,5,6]] transpose(A) // [[1,4],[2,5],[3,6]] |
transpose of a matrix |
ones | ones | disp(ones(3)) // 3x3 matrix of 1s disp(ones(3,2)) // 3x2 matrix of 1s disp(ones(3,1)) // column of 1s |
Matrix of ones |
eye | eye | disp(eye(3))// 3x3 identity matrix disp(eye(4)) // 4x4 matrix of 1s disp(eye(10)) // column of 1s |
Generates identity matrices |
zeros | zeros | disp(zeros(3)) // 3x3 matrix of 0s disp(zeros(3,2)) // 3x2 matrix of 0s disp(zeros(3,1)) // column of 0s |
Generates zero matrices |
rand | rand | disp(rand()) // random no in [0,1] disp(rand(3)) // 3x3 random disp(rand(3,2)) // 3x2 random disp(rand(3,1)) // column of random |
Generates matrix of random numbers in [0,1] |
randi | randi(N,rows,cols) | disp(randi(5)) // random integer in {1,2...5} disp(randi(5,3)) //3x3 matrix of random integers in {1,2...5} disp(randi(5,3,2)) // 3x2 random in {1,2...5} |
Generate random integer matrices |
diag | diag(D) |
disp(diag([5,3,2])) // returns: // [ [5, 0, 0], // [0, 3, 0], // [0, 0, 2] ] |
Diagonal matrix from an array |
reshape | reshape | reshape([1,2,3,4,5,6],2,3) // [1,2,3; 4,5,6] |
Reshape a vector or a matrix |
A(rowrange,colrange) A(1:3,1:3) A(10,10) A(end,end-1) |
get(A,rowrange,colrange) get(A,[1,2,3],[1,2,3]) get(A,10,10) get(A,0,-1) |
A=rand(10,10);disp(A) B=get(A,[1,2,3],[2,5,7]) disp(B) B=get(A,':',[1,2,3]) disp(B) // gets all rows & first 3 cols |
Get a submatrix |
A(rowrange,colrange)=B A(1:3,1:3)=B A(end-5:end,:)=2 a(arrayrange)=b a(1:3)=[10 20 30] a(1)=10 a(end-2)=8 |
set(A,rowrange,colrange,B) set(A,[1,2,3],[1,2,3],B) set(A,range(-5,0),':',2) set(a,arrayrange,b) set(a,[1,2,3],[10,20,30]) set(a,1,10) set(a,-2,8) B can be a matrix or a number rrange and crange can be number or arrays or ':' |
Matrix example: A=rand(5,5) set(A,range(1,3),range(1,3),0) disp(A) // sets first 3 rows and cols to 0 set(A,range(1,3),range(1,3),randi(2,3,3)) disp(A) // sets first 3 rows and cols to random in {1,2} Array example: A=[1,2,3,4,5,6] set(A,2,10)// A(2)=10 :: sets 2nd elem to 10 set(A,0,100) // A(end)=20 :: sets last elem to 100 set(A,-1,20) // A(end-1)=20 :: sets end-1 (last but one) elem to 20 disp(A) // [1, 10, 3, 4, 20, 100] |
Set a submatrix or a subarray |
repmat | repmat(mat,rows,cols) | A=rand(2,3) B=repmat(A,4,5) disp(B) |
Repeat matrix |
kron | kron(X,Y) | A=[[1,2,3],[2,3,4]]; Y=[[1],[1],[1]]; display(kron(A,Y)) |
Kronecker tensor product |
union | union(X,Y) | A=[1,2,3,4]; B=[5,3,10]; display(union(A,B)) //[1,2,3,4,5,10] |
Union of two sets |
unique | unique(A) | A=[10,2,3,3,4]; display(unique(A)) //[2,3,4,10] |
Unique items of a set |
sparse(I,J,K) | sparse(I,J,K,nRows,nCols) | A=sparse([1,2],[1,2],[10,10],10,10);
disp(A) |
Initiate a sparse matrix I - row indices J - column indices K - element values nRows - no of rows nCols - no of cols |
B=A | B=copy(A) | A=rand(4) disp(A) B=A B[0][0]=20 disp(A) // note: A changes // when B is changed C=copy(A); C[0][0]=100 disp(A) disp(C) |
For array and matrices B=A; will not actually copy A but only creates a reference Use B=copy(A) instead. |
C=A+B | C=add(A,B) | disp(add(3,4)) disp(add(ones(4,1),100)) disp(add(100,rand(1,4))) disp(add(ones(4),100)) disp(add(100,rand(4))) disp(add(ones(4),rand(4))) |
Universal add for number + number array + number array + array number + matrix |
C=A-B | C=sub(A,B) | disp(sub(3,4)) disp(sub(ones(4,1),100)) disp(sub(100,rand(1,4))) disp(sub(ones(4),100)) disp(sub(100,rand(4))) disp(sub(ones(4),rand(4))) |
Universal subtract for number - number array - number array - array number - matrix |
C=A*B | C=mul(A,B) | disp(mul(3,4)) disp(mul(ones(4,1),100)) disp(mul(100,rand(1,4))) disp(mul(ones(4),100)) disp(mul(100,rand(4))) disp(mul(ones(4),rand(4))) disp(mul(eye(4),rand(4))) disp(mul(rand(5,4),rand(4,3))) disp(mul(rand(5),rand(5,1))) disp(mul(rand(1,10),rand(10,1))) |
Universal multiply for number * number array * number array * array matrix(n by k) * matrix(k by m) |
C=A.*B | C=dotmul(A,B) | disp(dotmul(3,4)) A=ones(4) B=rand(4) disp(dotmul(rand(10,1),rand(10,1))) disp(dotmul(A,B)) disp(dotmul(eye(4),B)) |
Elementwise multiply for number .* number array .* array matrix .* matrix |
C=A/B | C=div(A,B) | disp(div(3,4)) disp(div(ones(4,1),100)) disp(div(100,rand(1,4))) disp(div(ones(4),100)) disp(div(100,rand(4))) disp(div(ones(4),rand(4))) |
Universal divide for number / number array / number array / array number / matrix |
C=A./B | C=dotdiv(A,B) | A=rand(1,4) B=mul(100,ones(1,4)) disp(dotdiv(A,B)) C=add(rand(10),1) disp(dotdiv(rand(10),C)) disp(dotdiv(eye(4),rand(4))) |
Elementwise divide for number ./ number array ./ array matrix ./ matrix |
C=A^B | C=pow(A,B) | disp(pow(3,4)) disp(pow(ones(4,1),100)) disp(pow(100,rand(1,4))) disp(pow(ones(4),100)) disp(pow(100,rand(4))) disp(pow(ones(4),rand(4))) disp(pow(eye(4),rand(4))) |
Universal power for number ^ number array ^ number array ^ array number ^ matrix matrix ^ number matrix ^ matrix |
A(:) | colon(A) | disp(A=rand(4)) disp(colon(A)) |
List all columns as vector |
x=A\b | x=linsolve(A,b) | A=[[2,3,4],[1,1,1],[1,0,1]] b=[[9],[3],[2]] x=linsolve(A,b) disp(x) disp(mul(A,x)) |
Linear solve (or) mldivide solve a sys of linear equations |
all | all | all([[true,true],[true,false]]) // false all([true,true],[true,true]]) // true |
If all elements are true, returns true Multi-dimensional |
any | any | any([[false,false],[false,false]]) // false any([false,false],[true,false]]) // true |
If any element is true, returns true Multi-dimensional |
Not available | map(funcion,arg1,arg2,arg3,...) | map(x=>x>3, [1,2,3,4,5]) // [false,false,false,true,true] map(x=>x>3, [[1,2,3],[4,5,6]]) // [[false,false,false],[true,true,true]] map((a,b)=>a>b, [[1,2,3],[4,5,6]],3) // [[false,false,false],[true,true,true]] map((a,b)=>a+b, [[1,2,3],[4,5,6]],3,[[1,2,3],[4,5,6]] ) // [[5,7,9],[11,13,15]] |
Multi dimensional map: Applies function across all elements, If any arg is not an array, uses the value instead Considers two arguments at a time until the last |
exp | exp(number or complex or array or complex array | exp(1) // 2.718.. a=exp(new cx(0,Math.PI/2)) disp(a)// 0+1i i.e. a.re=0 a.im=1 |
Multi dimensional universal exponention function |
Contributing
Your contributions are welcome. Please follow the instructions below to contribute.
You can contribute to this repository by following these steps: - Fork the repository and clone it locally, and create a new branch. - Include your contribution in theMatlab.js
file. For example:
var add2 = function(a){
return a+2;
}
- Write testing scripts for the new function in
tests/run_tests.js
file by includingtest("your_function_name(args)","expectedoutput")
.-
An example would be
test("add2(4)",6)
-
An example would be
- Test on the browser
-
Serve and open
index.html
and click the "Run tests" button on the web page displayed. This will callrun_tests.js
and print results in a popup.
-
Serve and open
- Test on Node
-
To initiate the testing suite, execute
npm test
from the terminal.
-
To initiate the testing suite, execute
- If these tests pass, you may commit and raise a pull request to the
main
branch.
Unit testing
To perform a quick check, you can run some unit tests on the browser by clicking the "Run tests" button.
Issues
For bugs, feedback and feature requests, raise an Issue in the GitHub repository
License
MIT License
Copyright (c) 2021 Vivek T Ramamoorthy