0.2.0 • Published 1 year ago

matlabjs v0.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

MatlabJS

A lightweight JavaScript library for MATLAB/Octave users

This library gives you some essential array and matrix functions written in JavaScript for easing your scientific computing projects or code conversion from Matlab or Octave.

Documentation

To see how it works, go to https://VivekTRamamoorthy.github.io/MatlabJS. The library is loaded on the webpage and you may start testing it in the console. The website also contains a cheatsheet.

Examples

    tic()
    a=linspace(0,1,100) 
    disp(a) ;
    b=eye(4); 
    c=rand(4); 
    d=mul(b,c) ;
    disp(d)
    toc();

Using in your projects

Method 1: CDN (Loads the latest update)

  • Include the following script tag to your html. This will include all updates and bug fixes.
<script src="https://cdn.jsdelivr.net/gh/VivekTRamamoorthy/MatlabJS/Matlab.js"></script>

This would only give the standard functions. To use plotting tools and linsolve function, additionally includeplotlib.js andndarray.js files.

Method 2: Including file using script tag

  • Download theMatlab.jsfile to your project folder.
  • Include the file in a script tag:
<script src="Matlab.js"></script>

Node:

Install using npm install matlabjs

Use in your projects like below

const MatlabJS = require("matlabjs")
let A = MatlabJS.zeros(10,10) // [[0,0,0,...],  [0,0,0,...], [0,0,0,...], .... ]

or

const {add, linspace} = require("matlabjs")
let A = add(linspace(0,1),200) // [ 200, 201.010101... , 202.020202... , ...]

A note of caution

  • Operator overloading is not yet permitted in JavaScript and doesn't seem like it will be anytime soon. So it is not possible to writec=A*b for matrices in Javascript. Instead, one has to resort to the syntactically inconvenient universal functions, for example,c=mul(A,b).
  • When using the script tag method, all functions are loaded into the global scope usingvars and users may overwrite them if needed like in Matlab. If you prefer a namespace import, use it as a module.
  • The code may not be optimised for efficiency. For intensive computations, users can manually optimise the code for their use case if performance is an issue.
  • This project is in its initial stage. Additional functionalities may be included as time progresses.

Contributing

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 intests/run_tests.js file by includingtest("your_function_name(args)","expectedoutput").
    • An example would betest("add2(4)",6)
  • Test on the browser
    • Serve and openindex.html and click theRun tests button on the web page displayed. This will callrun_tests.js and print results in a popup.
  • Test on Node
    • To initiate the testing suite, executenpm test from the terminal.
  • If these tests pass, you may commit and raise a pull request to themain branch.

List of functions

Use left or right arrow keys to scroll if the the table is not fully visible.

Matlab functionMatlabJS equivalentExample usageDescription
tictic()Starts recording time
toctoc()tic(); t=toc();Prints elapsed time since start
clcclc()clc()Clears console
linspacelinspaceA=linspace(0,1)// [0 .1010.. 1] B=linspace(10,20,3)// [10,15,20]Produces linearly spaced array.
logspacelogspaceA=logspace(1,1000,4)// [1 10 100 1000]B=logspace(1,25,3)// [1,5,25]Produces logarithmically spaced arrays.
disp,displaydisp,displayA=linspace(0,1)B=linspace(10,20,3)disp(A)display(B)Displays matrices and arrays in console
isfieldisfield(struc,fieldname)struc={x:10,y:100}isfield(struc,'x')// trueisfield(struc,'a')// falseChecks the presence of fieldnames in a structure
sizesize(A)A=[[1,2,3],[3,4,5]]size(A) // [2,3]Dimensions of a matrix or array
lengthA.lengthlength(A)A=[1,2,3,3,4,5]A.length // 6length(A) // 6Length of an array
findfindA=[1,2,0,0,4,5]find(A) // [1, 2, 5, 6]Find nonzero elements
sortsort()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
sumsumA=[1,2,3]sum(A) // 6B=[[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
absabsA=[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
sqrtsqrtA=[1,4,2]disp(sqrt(A))// [1,2,1.414] A=rand(4)disp(A)disp(sqrt(A))Square root of a number, array or matrix
setdiffsetdiffA=[4,3,1,5]B=[5,3,7,8]setdiff(A,B) // [1,4]Set difference (sorted)
minminA=[1,3,-5,9]disp(min(A)) // -5B=[[1,2,3],[4,5,6],[7,8,9]]disp(B)disp(min(B,1)) // elemwise mindisp(min(B,4)) //disp(min(B,[],1)) // column mindisp(min(B,[],2)) // row minMinimum of an array or matrix
maxmaxSimilar to minMaximum of an array or matrix
a:b:crange(a,b,c)range(2,0.5,4)// [2,2.5,3,3.5,4]Array from a to c in steps of b
triutriu(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 matrixConcatenate 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 matrixConcatenate columns of two matrices
A'transpose(A)A=[[1,2,3],[4,5,6]]transpose(A)// [[1,4],[2,5],[3,6]]Transposes a matrix
onesonesdisp(ones(3))// 3x3 matrix of 1sdisp(ones(3,2))// 3x2 matrix of 1sdisp(ones(3,1))// column of 1sMatrix of ones
eyeeyedisp(eye(3))// 3x3 identity matrixdisp(eye(4))// 4x4 matrix of 1sdisp(eye(10))// column of 1sGenerates identity matrices
zeroszerosdisp(zeros(3))// 3x3 matrix of 0sdisp(zeros(3,2))// 3x2 matrix of 0sdisp(zeros(3,1))// column of 0sGenerates zero matrices
randranddisp(rand())// random no in [0,1]disp(rand(3))// 3x3 randomdisp(rand(3,2))// 3x2 randomdisp(rand(3,1))// column of randomGenerates matrix with values uniformly random in 0,1
randirandi(N,rows,cols)disp(randi(5))// random num in {1,2...5}disp(randi(5,3))disp(randi(5,3,2))// 3x2 random in {1,2...5}Generate random integer matrices with values in[0,1,2,...,N]
diagdiag(D)disp(diag([5,3,2]))// returns:// [ [5, 0, 0],// [0, 3, 0],// [0, 0, 2] ]Diagonal matrix from an array
reshapereshapereshape([1,2,3,4,5,6],2,3)// [1,2,3; 4,5,6]Reshape a vector or a matrix
Getting values 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 colsGet values of a submatrix
Setting values in matrices A(rowrange,colrange)=BA(1:3,1:3)=BA(end-5:end,:)=2a(arrayrange)=ba(1:3)=[10 20 30]a(1)=10a(end-2)=8set(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)Matrix example:A=rand(5,5)set(A,range(1,3),range(1,3),0)disp(A)// sets first 3 rows and cols to 0set(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)=10set(A,0,100) // A(end)=20set(A,-1,20) // A(end-1)=20disp(A) // [1, 10, 3, 4, 20, 100]Set values to a submatrix
repmatrepmat(mat,rows,cols)A=rand(2,3)B=repmat(A,4,5)disp(B)Repeat matrix
kronkron(X,Y)A=[[1,2,3],[2,3,4]];Y=[[1],[1],[1]];display(kron(A,Y))Kronecker tensor product
unionunion(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
uniqueunique(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=AB=copy(A)A=rand(4)disp(A)B=AB[0][0]=20disp(A)// note: A changes// when B is changedC=copy(A); C[0][0]=100disp(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+BC=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-BC=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*BC=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.*BC=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/BC=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./BC=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^BC=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\bx=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 Uses ndarrayjs Include ndarray.js file in your project.
allallall([[true,true],[true,false]])// falseall([true,true],[true,true]])// trueIf all elements are true, returns true Multi-dimensional
anyanyany([[false,false],[false,false]])// falseany([false,false],[true,false]])// trueIf any element is true, returns true Multi-dimensional
Not availablemap(function,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
expexp(number or complex or array or complex arrayexp(1) // 2.718..a=exp(new cx(0,Math.PI/2))disp(a)// 0+1i i.e. a.re=0 a.im=1Multi dimensional universal exponention function

License

MIT License 2.0

Vivek Thaminni Ramamoorthy

0.2.0

1 year ago

0.1.2

2 years ago

0.1.1001

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago