Table of Contents

Introduction

Contact

Language Features

Standard Functions

Examples

Changes

Credits

Future

License

About

Introduction

MathCortex is a open source numerical computing environment and a lightweight programming language.

It is written in JavaScript and works on web browsers.

Main features are:

All the operations are done on browser for fast and server independent computing. The code is first compiled to a simple JavaScript intermediate code. The generated JavaScript code is evaluated and runs very fast on the browser.

Language is still being developed.

Contact

Check MathCortex on Github
mathcortex@gmail.com
@mathcortex on Twitter.

License

The compiler code is distributed under GPL license. MathCortex on Github

The virtual machine code(cortex_asm_vm.js) and cortex run time library(cortex_runtime.js) is under MIT license.

Benchmark

In single processor environment with using the spectralnorm example at: http://benchmarksgame.alioth.debian.org/u64q/performance.php?test=spectralnorm , there is only x2 difference between MathCortex and native C application and when multi processor is enabled(openmp) there is x5.2 speed difference with native C application.

Compared to Python, MathCortex runs nearly 50 times faster for spectralnorm example.

CMathCortexPythonJavaScript
5500 (single)4.0 s8.8 s8.4 s
10000 (single)13.6 s27.5 s27.2 s
5500 (multi)1.7 s8.8 s437 s8.4 s
10000 (multi)4.5 s27.5 s1415 s27.2 s

Tests are done using Firefox 38.0.1, Visual Studio 2010, Python 3.4.3

Language Features

Syntax

Syntax is heavily influenced by JavaScript and C.

Statements are seperated by semicolumn ;.The last statement of a script need not to end with semicolumn.

Assignment operator is =.

Function Call

Function call operator is (..).

s = sin(pi/5);

Matrix Values

[..] is matrix creation if it does not follow a matrix variable. ; is used to seperate rows. , is not required to seperate columns but adviced. ( [1 2] is ok but [1 -2] will be [-1] which may cause confusion)

m1 = [1,2;5,6];
m2 =  [ 1  2;
        2  4];
m3 = @[-1 -2; 2 -3]; // verbatim mode. (without @ m3 would be [-3; -1])
		
		

Matrix Indexing

[..,..] is matrix indexing operator if it follows a matrix variable. , is used to seperate row and column index.

m = [1,2;5,6];
m21 = m[1, 0];        // indices are zero based
m[1, 1] = 66;

Ranges
: can be used to specify ranges in matrix indexing. It can be used for both assinging and reading. -1 means last of the index. Using range notation can cause slow down if not used properly.
m = [1,2,3; 4,5,6; 7,8,9];

m1 = m[0, :];          // m1 will be [1,2,3]
m2 = m[1, 0:1];        // m2 will be [4,5]
m3 = m[:, 1:-1];       // m3 will be [2,3; 5,6; 8,9]

m[1:2, 0:1] = eye(2);  // m will be [1,2,3; 1,0,6; 0,1,9];

Types

Type system is static with full type inference so that no explicit declarations required.

Currently supported types are:


r = -3.14;

m = eye(3);

b1 = true;
b2 = (1 == 2);

s1 = "hello";
s2 = " world : ";
s = s1 + s2 + r;

Note that declarations are implicit. But once a variable is declared as one type, its type can not change

Operators

Currently implemented operators are (from lowest to highest precedence):

Name Operator Description
Assignment =, =/, =*, =+, =-
Logical OR || bool only
Logical AND && bool only
Relation ==, !=, <, >, <=, >= Reals supports all operators
Matrices and strings support ==, != only.
Colon : a = 1:3, 1:2:10, 10:-2: 4
Addition / Subtraction +, - Supported for reals and matrices. String only support +
Multiply / Division / Elementwise *, /, .*, ./, % Matrices support *, .*, ./, %
Reals support *, /, %
Logical NOT ! bool only
Matrix Transpose ' Matrices
Prefix ++, -- Reals and matrices
Postfix ++, -- Reals and matrices
Function call / Array subscripting/ Member and method access (), [], .
Parenthesis ( .. ) Ordering expressions (3+4)*3
Supported Matrix Operators

Matrix to matrix operations : +, -, *, ==, !=

Elementwise matrix multiply and divide : .*, ./

Matrix to scalar operations : +, -, *, /

Control statements

Currently loop, loop0, while, if/else, for can be used for control and loop statements.

Syntax for while, for, if/else is just like JavaScript and C. break, continue is supported like C. { } can be used(optional) to define blocks

loop, loop0

These are simplifed version of for loop. loop0(i, count) iterates i from 0 to count-1. loop(i, start, end) iterates i from start to end-1.

x = 0.5;
if( x < 0)
{
   disp("x is negative");
}
else            // { } is optional
   disp("x is positive");

loop0(i, 10)
  disp(i);      // prints 0 to 9
  
loop(i, 2, 5)   
  disp(i);      // prints 2 to 4
  
for(i = 0; i < 10; i++)
  disp(i);      // prints 0 to 9

i = 10;
while(i > 6)
{
   disp(i);     // prints 10 to 6
   i--;
}
  

Defining functions

Functions are defined without giving any type information with support to local varibles.

function add(a, b)
{
    return a+b;
}

r = add(5, 6);              // 11
m = add([5, 2], [6, -1]);   // [11, 1]
s = add([5, 2], 3);         // [8, 5]

Because of parameters are declared implicitly and mathcortex is static typed, they are generic types (like templates in C++). Three different machine code will be generated for the example above.

Global and local variables

Variables defined inside a function scope will be local and will not be visible anywhere. Global and local usage is similiar to Python: global keywords should be used to create or write to a global variable. 'global' keyword is not required to read from global variable. Global variables are declared at top most scope, outside of any function code.

First class functions

MathCortex has support for full type inference with implicit typing and also it supports generic programming.

// first class function example: functions can be used as a variable or parameter 
// f, g, h are some functions
function f(x) 
{
    return x; 
} 

function h(x)
{
    return x+2;
}

function g(x)
{
    return x+1;
}

d1 = g;             // d1 is a function variable
d1 = f;             // function variables can change value
d2 = h;             // d2 is another function variable 

d3 = d2;            // function variables can be assigned to one other

r = d1(1);    
m1 = d2([2]);       // these all functions also support generic types(like templates) 
m2 = d2("hello ");
s = d3("world ");   

d4 = f(h);          // function variables can be passed as argument

You can make powerfull yet simple statements with type inference and generic programming without any runtime costs.

//type inference and generics example
function add(a,b)
{
    return a+b;
}

r = add(3, 5);                     // r will be 7
m = add([1,2;4,5], [1,-1;-2,-4]);  // m will be [ 2, 1; 2, 1 ]
s = add( "hello" , 3);             // s will be 'hello3'




//type inference and generics works with first class functions.
//type resolution will be done in compile to so there is no runtime cost.
function f(x) => x+1;
function g(x) => x-1;
function m(x)
{    
  if (x == 1)    
    return f;  
  else
    return g; 
} 
r = m(1)(3);        // m(1) returns function f, f(3) return 4 so r is 4
A = m(2)( eye(3));  // m(2) returns function g, g((eye(3)) returns matrix: 0, -1, -1; -1, 0, -1; -1, -1, 0
Lambda functions

MathCortex supports lambda/anonymous first class functions

// Lambda syntax allows shorter anonymous function definitions
f1 = function (a,b) => a + b; 
f2 = (a,b) => a + b; 
f3 = () => 5; 
f4 = (a) => a + 5;
// also name can be given for non anonymous version
function f(x) => x+1;
Defining multi return functions:

Functions with more than one return value can be defined like the following example

//user multi return functions:
function [a,b] = mf(x,y,z)
{
    a = x + z;
    b = y + z;
}

[a b ] = mf(3,5,6);

Classes

Classes are new feature. It is still in beta state.
// class definition is like function definition and also constructor
// all local varibles becomes members. 'var' keyword should be used for local variables
class Point3d(a,b,c) 
{
  // x, y, z are members	
  x = a; 
  y = -b;
  z = rand(4, 4);
	
  // l is a local variable 
  var l; 	
  l = 3;
}

a1 = Point3d(0, 2, 5);
a2 = Point3d("str", 6, 220);
a3 = Point3d(110, 2, 5);
bb = Point3d(0, 0, [2]);
Ex nihilo definition and instantiation
p1 = class Point3{ p1 : 2, p2 : 3, p4 : "aa"};
p2 = Point3(4, [6], "aaa");

// anonymous class without type name
p3 = class { p1 : 2, p2 : 3, p4 : "aa"};

// anonymous class with anonymous member
p4 = class { p1 : 2, p2 : 3, p4 : "aa", m1 : (a, b) => a + b };
Methods
class C1()
{     
  a = 4;
  
  function m2(x, y, z)
  {
    return x + y * z;
  }
  
  function m3() => m2(1, 2, 3) + a;
} 

a1 = C1(); 
d1 = a1.m3();

class C2()
{ 
  a=4;  
  
  function m2() => a++; 
  function m3(x) => x + m2(); 
} 

a1 = C2(); 
d1 = a1.m3(-2); 
d2 = a1.m3(-2);

Comments

C and JavaScript style comments are supported.

/*  Multi 
    line 
    comment */
		 
x = 5;      // this is a single line comment

Standard Functions

Matrix eye numcols numrows linspace ones rand randn zeros

Matrix Algebra cholesky det eig fft inv linsolve lu svd

Stats diff mean std sum variance

Plot plot imread imshow title

Elementary abs acos asin atan atan2 ceil cos exp floor fmod

Elementary log min max pow random round sqrt sin tan

Utility clear clc close error tic toc typeof

Animation anim animdraw animstop animsize

inv
Inverse of a matrix
Y = inv(X)
det
Determinant of a matrix
d = det(X)
disp/print
Displays variables
disp(X)
trans
Transpose of a matrix
Y = trans(X)
eye
Creates identity matrix
X = eye(n)
zeros
Creates a matrix filled with zeros
X = zeros(n)
X = zeros(m,n)
ones
Creates a matrix filled with ones
X = ones(n)
X = ones(m,n)
rand
Creates a random matrix where elements are between 0 and 1. Use function 'random' to generate scalar values
X = rand(n)
X = rand(m,n)
randn
Creates a random matrix from gaussian(normal) distribution
X = randn(n)
X = randn(m,n)
Elementary
abs(x), acos(x), asin(x), atan(x), atan2(y,x), ceil(x), cos(x), exp(x), floor(x), log(x), max(x,y,z,...,n), min(x,y,z,...,n), pow(x,y), random(), round(x), sin(x), sqrt(x), tan(x)
sum
Sum of all elements
s = sum(X)
mean
Mean of all elements
m = mean(X)
std, variance
Standart deviation and variance of all elements
s = std(X), v = variance(X)
diff
Difference between adjacent elements of X
Y = diff(X)
linspace
Generate linearly spaced vectors
y = linspace(a,b)
y = linspace(a,b,n)
lu
lu decomposition
[d p] = lu(A)
linsolve
Solve linear systems of equations
x = linsolve(A,b)
svd
Singular value decomposition
X = svd(X)
[U S V] = svd(X)
eig
Find eigenvalues and eigenvectors
L = eig(X)
[L V] = eig(M)
fft
Discrete Fourier Transform. Returns real and imaginary parts of Fourier transform
Re= fft(X)
[Re Im] = fft(X)
cholesky
Cholesky decomposition
L = cholesky(X)
plot
Plot 2d graph
plot(X)
plot(X,Y)
plot(X,Y,opts)
plot(X1,Y1,X2,Y2)
plot(X1,Y1,opts1,X2,Y2,opts2)

opts is a combination of characters each of the following meaning:

Line Colors:
  • g : green
  • r : red
  • b : blue
  • k : black
  • c : cyan
  • m : magenta
  • y : yellow
  • r : red
Point symbols:
  • o : circle
  • d : diamond
  • x : cross
  • s : square
  • ^ : triangle
  • - : show line
  • . : small dot
tic, toc
Timer functions
 tic()
 ... 
 toc()
clear
Clear a variable or all variables
clear X
clear all
clc
Clears output window
 clc 
close
Closes open figures
 h = plot([1,2,5]); 
close(h);
close all;
error
Produces runtime error
error("invalid data")
typeof
Returns type id of a value. For bools 1, reals 2, matrices 3, strings 4, function and delegates 5 and 6
typeof([0] + 3);
numcols, numrows
Get number of rows or column of a matrix
c = numcols(X);
r = numrows(X);
imread
Reads image from url. Requires preloading of image. See examples.
preload { "url" }; 
...
[r g b] = imread("url");
imshow
Shows image
imshow(I)
imshow(R, G, B)
title
Set title of plot or image
title("sine of x")
title(h, "sine of x")
anim
Creates and image animation.
function update(id)
{
    animdraw( id, 255 * ones(100,100) );
}

anim(update, 60); 
animdraw
Updates animation image with given gray or rgb matrix. Should be called inside draw callback function. See anim example.
animdraw(id, R, G, B)
animdraw(id, G)
animstop
Stops animation
animstop
animsize
Zooms size of animation canvas
animsize(width,height)

Change History

Check Beta

    24 jan 2017
  • global local variable shadowing rules are changed: it is similiar to pythons. global and var keywords are added.
  • new operators: colon ":" operator, ex: a = 1:3, 1:2:10, 10:-2: 4 % mod operator *=, /= operators for real and matrices +=, -= operator on types real, matrix, string
  • ! (logical not) precedence upgraded to unary level. () [] . all the same precedence
  • continue keyword
  • classes: class Point3d(a,b,c) { x = a; y = -b; z = rand(4,4); } a1 = Point3d(0,2,5); a2 = Point3d("str",6,220); a3 = Point3d(110,2,5); bb = Point3d(0,0,[2]); p1 = class Point3{ p1:2, p2 : 3, p4:"aa"}; p2 = Point3(4,[6], "aaa"); class C1(){ a=4; function m2(x,y,z) => x+y*z; function m3() => m2(1,2,3)+a; } a1 = C1(); d1 = a1.m3(); class C2(){ a=4; function m2() => a++; function m3(x) => x+m2(); } a1 = C2(); d1 = a1.m3(-2); d2 = a1.m3(-2);
  • short form(lambda) functions: function f(x) => x + 1; x1 = function (a,b) => a + b; x2 = (a,b) => a + b; x3 = () => 5; x4 = (a) => a + 5; x5 = function(a,b) => { a++;return a + b; }; y1= x1(2,4); y2= x2(4,5);y3= x3();y4 =x4(2);y5 = x5(-3,4);y1 == 6 && y2 == 9 && y3 == 5 && y4 == 7 && y5 == 2
  • user multi return functions: function [a,b] = hede(x,y,z) { a = x + z; b = y + z; } [a b ] = hede(3,5,6);
  • typeof function
    14 june 2016
  • new functions: fft, diff, mean, std, max, min, title, animsize, fmod
  • new layout system for plot and image
  • animation is working again
  • several bug fixes and better error checking in standard library functions
  • best effort runtime error reporting.(chrome and ff for now)
  • while break bug fix for js output
    16 dec 2015
  • up to x1000 speed up by direct JavaScript code generation instead of byte code generation.
  • new license: gpl for compiler, mit for library and asm code
  • code uploaded to github
  • new login system. openid removed
  • more structured code: namespace cortexParser added, single compiler file
  • AST generation implemented for statements
  • readable javascript code generation
  • main window changes: help col removed. new information controls on header div
  • new benchmarks
  • latex cheatsheet
  • fix for gui slow down (measured 8 secs load time) when history gets huge
  • code tab control fixes
    15 may 2015
  • automatical 'return 0' statement at the end of function if nor previously defined
  • new plot features: dual plot, line and point specs
  • randn normal distribution
  • matrix verbatim mode @[-3 -1;-2 -1]
  • 'E' is also accepted for floating points
  • asmjs.js code generation changed for speed up

  • gui:
  • plot interaction is improved
  • ace and flot libraries updated
  • csv like variable import window
  • command line window improved
    29 july 2014
  • assignment (=) is now seen as an operator.
    various bugs are fixed arised from previous improper implementation of =
  • postfix and prefix increment decrement for reals and matrices.
    postfix matrix inc/dec gives error for efficiency
    19 nov 2013
  • first class functions implemented with full support for generics, delegates and type inference(still in alpha stage)
  • new functions:
    clear (limited to top level only)
    print(alias to disp)
    tic, toc : timer functions
    close :closes open figures
    clc : clears output window
    _heap, _stack, _compile, _dotests : debugging purposes
    anim, animstop, animdraw: function for animated images.
  • c style for loop support
  • break for while, loop, and for
  • support for: blocks without { } for if, while, etc
  • strings now supports escape characters \\, \n,\t,\",\' properly
  • imread.php bug fix
  • code generation improvements
  • latex style support
  • command style function call support, that is calling functions without ()
  • various css improvements and fixes
  • Parser comment bug fix.
  • new file structure
  • eigenvectors fix with multiassignment fix
  • auto login timeout increased to 60 days from 15.
    2 aug 2013
  • documents can now be stored at server with a directory structure.
  • gui is changed to multi document view style.
  • new editor: ace
  • login functionality via Openid.
  • matrix ops .*, ./ with the same precedence with *, /
  • : operator ex: A[ 1:2,3:4], A[:,1], A[1,:], A[1:2,3], A[:,:], A[0,:]
  • new functions: ones, linspace
  • image functions: imread, imshow,
  • preload keyword for preloading images(a requirement of browsers).
  • format short is default. fix for 'disp' formating
  • better matrix print
  • plotVar, imageVar support for multi views in a script call
  • fix: checkahead bug
    18 April 2013
  • better error reporting.
  • function delegate bug fix with perf improvement
  • single indexer for matrices.
  • type inference for recursion function were not working.
  • optional function return values with keywords real, matrix, bool, string.
  • better asm_js lang. variables stored in heap like struct. there is no vars or var types in asm.
  • direct url link to programs.
  • variable view reworked
    2 April 2013
  • user functions ex: function f(a,b) { return a+b; }
  • function delegates with zero parameters
  • no more ; after block { }
  • rvalue referance for matrix operation
  • new layout for web page
  • no kickstart dependency
  • strings with +, == ,!= operators are implemented
  • matrix == ,!= operators are now supported
  • white space and comments skiping parser bug fix

Future

Some major features on roadmap are

Credits

Numeric JavaScript

Let's Build a Compiler, by Jack Crenshaw

Ace Code Editor

Flot - JavaScript plotting library

HTML KickStart CSS

About Me

My name is Gorkem Gencay. I have started programming nearly 20 years ago. I am working as a professional programmer for more than 12 years. I mostly used C/C++ for work.

I have started this project mainly for fun. Than I thought that I can use it for simple scripting which has support for built-in matrix and numerical computations.

I also wanted that it can be easily accessed and integrated. By doing stuff on web browser, it will be platform independent, no installation or setup, can be accessed from everywhere.

It is my first web application. My first JavaScript, HTML and CSS experience.


Gorkem Gencay
Copyright (c) 2012-2018