How to use mathjs

Comprehensive mathjs code examples:

How to use mathjs.column:

94
95
96
97
98
99
100
101
102
103
104
    Aeq = S.concat(Aeq);
    beq = S.concat(beq);
    [V, nr, nre] = lcon2vert(A, b, Aeq, beq, TOL);


    I.vert = V;
    I.lcon = [math.column(A, nr), math.column(b, nr), math.column(Aeq, nre), math.column(beq, nre)];
}



How to use mathjs.isNumeric:

0
1
2
3
4
5
6
7
8
9
const {exportsCommandName} = require("../../util/loader")
const discord = require('discord.js');
const { isNumeric } = require("mathjs");

module.exports.run = async (bot,message,args) =>{
    let time = isNumeric(args[0]) ? args[0] : 10000 ;
    if(args[0] === "stop"){
        stop(bot,message)
        return;
    }

How to use mathjs.typeOf:

174
175
176
177
178
179
180
181
182
183
from_points(var_1, var_2, var_3, var_4) {
    let point_1, point_2;

    if (var_3 == undefined && var_4 == undefined) {
        // Two points are given
        let is_matrix = (x) => math.typeOf(x) == "Array" && math.size(x) == 2;

        if (is_matrix(var_1) && is_matrix(var_2)) {
            function generate_point(variable) {
                return new Point(variable[0], variable[1]);

How to use mathjs.prod:

7
8
9
10
11
12
13
14
15
16
// média (retorna 2)
console.log('média:', math.mean([2, 1, 3]));
// mediana (número entre o maior e o menor -> 2)
console.log('mediana:', math.median([2, 1, 3]));
// produto (multiplicação)
console.log('produto:', math.prod([2, 1, 3]));
// quadrado (eleva cada elemento)
console.log('quadrado:', math.square([2, 1, 3]));
// cubo (eleva cada elemento)
console.log('cubo:', math.cube([2, 1, 3]));

How to use mathjs.sort:

53
54
55
56
57
58
59
60
61
optionsArray.push(numerator);
optionsArray.push(denominator);

question = `Arrange the following in ascending order: <br/>{&#8508;, ${number}, &radic;<span style="text-decoration: overline">${squareroot}</span>, &#8731;<span style="text-decoration: overline">${cuberoot}</span>, <sup>${numerator}</sup>&frasl;<sub>${denominator}</sub>}`;

answer = math.sort([Math.PI, number, Math.sqrt(squareroot), Math.cbrt(cuberoot), numerator/denominator]);

array.push(optionsArray);
array.push(answer);

How to use mathjs.integral:

48
49
50
51
52
53
54
55
56
57
58
59
}


// Função para Integrais
function integrate() {
  let x = document.getElementById("calc").value;
  let y = math.integral(x, 'x').toString();
  document.getElementById("calc").value = y;
}


// adiciona o evento "keydown" para capturar as teclas pressionadas

How to use mathjs.filter:

73
74
75
76
77
78
// aproximação para cima
console.log('aproximação para cima:', math.ceil([1.2, 2.5, 3.9]));
// expressão
console.log('expressão:', math.evaluate('(2 + 3) * 2'));
// filtro
console.log('filtro:', math.filter([1, 2, 2, 3], new RegExp(2)));

How to use mathjs.concat:

168
169
170
171
172
173
174
175
176
177
let block_b = math.add(results['AF'], results['BH']);
let block_c = math.add(results['CE'], results['DG']);
let block_d = math.add(results['CF'], results['DH']);

// Stack the results together
block_a = math.concat(block_a, block_b);
block_c = math.concat(block_c, block_d);
let mat_res = math.concat(block_a, block_c, 0)

// Get the size of the resulting matrix

How to use mathjs.resize:

155
156
157
158
159
160
161
162
163
164
if (targets.length != this.no)
    throw new Error('output length not match');

// transfrom to matrix from array
targets = math.matrix(targets);
targets = math.resize(targets, [this.no, 1]);

// calculate error terms for output
var outputError = math.subtract(targets, this.ao);
var dAo = math.map(this.ao, dsigmoid);

How to use mathjs.intersect:

19
20
21
22
23
24
25
26
27
28

//ISSUE!!!!! if the ray extends past the mirror, an intersection will be given where one doesn't exist
//COMPENSATE FOR THIS!!
intersectPoint(ray) {
  //intersection of lines formed by the mirror and ray, both defined by two points
  let intersection = intersect(this.endpoint1, this.endpoint2, ray.position, [
    ray.position[0] + ray.direction[0],
    ray.position[1] + ray.direction[1],
  ]);
  if (intersection == null) {

How to use mathjs.equal:

13
14
15
16
17
18
19
20
21
22
 * */
getIndexRow : function(vector, number) {
    var size = math.subset(math.size(vector), math.index(0));
    for(var index = 0; index < size; ++index) {
        var value = math.subset(vector, math.index(index));
        if( math.equal(value, number) ) {
            return index;
        }
    }
}

How to use mathjs.unaryMinus:

100
101
102
103
104
105
106
107
108
109
var c = poly.slice(0, end);


// Remove small leading coefficients that introduce infinities
function calc_d(coeff) {
    return math.unaryMinus(math.divide(coeff, c[0]));
}
var d = c.slice(1, c.length).map(calc_d);
while (!d.every(isFinite)) {
    c = c.slice(1, c.length);

How to use mathjs.config:

126
127
128
129
130
131
132
133
134
135
// rendered (and therefore "enabled") child elements.
// Context is affected.
private renderChildren() {
  // Apply the random seed before rendering so we have deterministic
  // output when rendering the node's children.
  Math.config({randomSeed: this.ctx.seed});
  this.renderedChildren = [];
  for (let i = 0; i < this.elem.children().length; i++) {
    // TODO(scott): Parsing of text nodes using .contents().
    // We should should handle programmatic gotos, for instance.

How to use mathjs.solve:

195
196
197
198
199
200
201
202
203
// incremental change in parameters
switch(Update_Type){
    case 1:					// Marquardt
        //h = ( JtWJ + lambda * math.diag(math.diag(JtWJ)) ) \ JtWdy;
        //h = math.multiply(math.inv(JtWdy),math.add(JtWJ,math.multiply(lambda,math.diag(math.diag(Npar)))));
        h = math.solve(math.add(JtWJ,math.multiply(lambda,math.diag(math.diag(JtWJ)))),JtWdy);
        break;
    default:					// Quadratic and Nielsen
        //h = ( JtWJ + lambda * math.eye(Npar) ) \ JtWdy;

How to use mathjs.eigs:

57
58
59
60
61
62
63
64
65
66
const validateDataResult = validateData({ ...dataForm });

if(validateDataResult){
    const matrixTransformered = transformMatrix(dataForm.A);
    const vectorTransformered = transformMatrix(dataForm.b);
    const eigs = mathjs.eigs(matrixTransformered);
    var flag= true;
    for(var i=0;i<eigs.values.length;i++){
        console.log(eigs.values[i])
        if(eigs.values[i]<0){

How to use mathjs.coth:

15
16
17
18
19
20
21
22
23
24
console.log(math.acos(0.5));  
console.log(math.sinh(0.5));   
console.log(math.cosh(0.5));   
console.log(math.tanh(0.5));   
console.log(math.sinh(0.5) / math.cosh(0.5));  
console.log(1 / math.coth(0.5));  
console.log(math.coth(2));   
console.log(1 / math.tanh(2));  
console.log(math.sech(0.5));  
console.log(1 / math.cosh(0.5));   

How to use mathjs.sinh:

21
22
23
24
25
26
console.log(math.coth(2));   
console.log(1 / math.tanh(2));  
console.log(math.sech(0.5));  
console.log(1 / math.cosh(0.5));   
console.log(math.csch(0.5));  
console.log(1 / math.sinh(0.5));  

How to use mathjs.xgcd:

0
1
2
3
4
5
6
7
8
9
10
11
const math = require("mathjs");


//small helped functions
let modInverse = (a, n) => {


    let cache = math.xgcd(a, n);
    //unpack matrix object
    let gcdresult = cache._data[0], inverse = cache._data[1];
    if (gcdresult != 1) {
        console.log("inverse non found");

How to use mathjs.mad:

7
8
9
10
11
12
13
14
15
16
17
18
function ellipseMad (points, _sigma) {
  const sigma = _sigma || 3.5
  const medianPoint = [median(points.map(p => p[0])), median(points.map(p => p[1]))]


  // remove outliers with Median Absolute Deviation (MAD)
  const madValue = [mad(points.map(p => p[0])), mad(points.map(p => p[1]))]


  const outliers = []
  const filteredPoints = points.filter(pt => {
    if (

How to use mathjs.rotate:

112
113
114
115
116
117
118
119
120
121
122
  const thetas = Array(n)
    .fill()
    .map((_, i) => (i * da) / (n - 1));
  return thetas
    .map((theta) => epicycloid(r0, k, theta))
    .map((p) => math.rotate(p, a0));
}


function epicycloid(r0, k, theta) {
  const kp1 = k + 1;

How to use mathjs.deepEqual:

24
25
26
27
28
29
30
31
32
33
  }

  const conjugateTranspose = math.transpose(math.conj(givenMatrix));
  const inverse = math.inv(givenMatrix);

  return math.deepEqual(inverse, conjugateTranspose);
};

module.exports = {
  sum: sum,

How to use mathjs.atanh:

193
194
195
196
197
198
199
200
201
202
}
let acoth = function(x){
  return Mathjs.acoth(x);
}
let atanh = function(x){
  return Mathjs.atanh(x);
}
let erf = function(x){
  return Mathjs.erf(x);
}

How to use mathjs.log10:

103
104
105
106
107
108
109
110
111
112
113
114
115
116


app.get('/app/log10/:num1', async (req, res, next) => {
    res.send(
        {


            log10: log10(Number(req.params.num1))


        }


    )

How to use mathjs.forEach:

0
1
2
3
4
5
6
7
8
const math = require('mathjs');

// Finds the sum of all the elements in an array
const sum = (array) => {
  let total = 0;
  math.forEach(array, (val) => {
    // Itterate through the array, adding to the total variable
    total += val;
  });

How to use mathjs.acos:

26
27
28
29
30
31
32
33
34
35
sphereAngleCoordinates() {
    const polarA = this.amplitudes[0].toPolar();
    const polarB = this.amplitudes[1].toPolar();

    const aphi = polarB.phi - polarA.phi;
    const ateta = math.acos(polarA.r) * 2;
    const atetaB = math.asin(polarB.r) * 2;

    if (atetaB.toFixed(PRECISION) == ateta.toFixed(PRECISION))
    {

How to use mathjs.acoth:

190
191
192
193
194
195
196
197
198
199
}
let atan = function(x){
  return Mathjs.atan(x);
}
let acoth = function(x){
  return Mathjs.acoth(x);
}
let atanh = function(x){
  return Mathjs.atanh(x);
}

How to use mathjs.tanh:

17
18
19
20
21
22
23
24
25
26
console.log(math.cosh(0.5));   
console.log(math.tanh(0.5));   
console.log(math.sinh(0.5) / math.cosh(0.5));  
console.log(1 / math.coth(0.5));  
console.log(math.coth(2));   
console.log(1 / math.tanh(2));  
console.log(math.sech(0.5));  
console.log(1 / math.cosh(0.5));   
console.log(math.csch(0.5));  
console.log(1 / math.sinh(0.5));  

How to use mathjs.index:

13
14
15
16
17
18
19
20
21
22
let index;
let scale;
let col;

for (let j = 0; j < nCols; j += 1) {
  index = math.index(math.range(0, nCols), j);
  col = matrix.subset(index);
  scale = norm(col, p);

  if (scale > 0) {

How to use mathjs.tan:

2
3
4
5
6
7
8
9
10
11
console.log(math.sin(2));  
console.log(math.cos(math.pi / 4));   
console.log(math.tan(0.5));  
console.log(math.sin(0.5) / math.cos(0.5));  
console.log(math.cot(2));   
console.log(1 / math.tan(2));  
console.log(math.sec(2));  
console.log(1 / math.cos(2));   
console.log(math.csc(2));   
console.log(1 / math.sin(2));   

How to use mathjs.isZero:

93
94
95
96
97
98
99
100
101
102
103
  math.isInteger(a)
  math.isNaN(a)
  math.isNegative(a)
  math.isPositive(a)
  math.isPrime(a)
  math.isZero(a)
}


//---
// Constants