How to create a matrix using math.js from a variable in javascript

502 Views Asked by At

Let's say I have a Vector for Variable Y which seems something like this:

VarY = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

And I would like to use math.js to convert it into a Vector of this kind: (so later I can actually use other math.js functions such as Multiply)

VarY: [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]

That is easily done by hardcoding it using math.matrix([[1],[2],...,[0]])

But since this vector will be variable, I am looking for a way to make it dynamic...

I was thinking in something like:

math.matrix(VarY);

But it does not allow variables that way.

EDIT ---

Extra details here:

I am receiving some data as an input, that is what you will see here as "XOriginal"

for(var i=0; i<26; i++){
VarY.push([XOriginal[i].splice(26,1)]); // @@@@ HERE I SAVE A COPY FOR ALL THE Y RESULTS OF THE ORIGINAL DATA
XOriginal[i].splice(26,1);
}

for ( i=0; i<26; i++) {
  VarY.push([0]);
}

At the end of this, my variable VarY when I use console.log, like this:

console.log('VarYReal: ' + VarY);

In my console, it appears like this:

VarYReal: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

Now, since this variable is not storing it as an array or as a matrix, that is the reason why I can not use math.multiply

1

There are 1 best solutions below

3
Mark On BEST ANSWER

math.js has a reshape() function. Once you have created a matrix from the original js array, you can use it to change to the matrix you want:

const math = require('mathjs')
let y = [0, 1, 2,  3, 4]
let m = math.matrix(y)  

console.log(m.size())     // [ 5 ]

math.reshape(m, [m.size()[0], 1])

console.log(m.size())     // [ 5, 1 ]
console.log(m.valueOf())  // [ [ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 4 ] ]