2

It looks like a too basic job. However, I can't do it.

I added math.js to my HTML code

<script src="js/math.min.js"></script>

I define a matrix in firefox console:

var M = math.matrix([[1,0,0,4],[0,1,0,2],[0,5,1,9],[11,2,3,1]]);

So far everything is good.

M
Object { _data: Array[4], _size: Array[2], _datatype: undefined }

Now, I want to access a single element of the matrix:

M.index(1,2)

And I get an error

TypeError: M.index is not a function

ar2015
  • 5,558
  • 8
  • 53
  • 110

2 Answers2

6

It looks like you need to use math.index.

M.subset(math.index(1, 2));

But the preferred method, as pointed out by it's author, is using .get.

M.get([1, 2]);

As of the time of this writing, this feature is preferred but documentation is still catching up.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • Thanks, it does work. But should it be such a long process compared with normal array? In other languages it is just like `M[1][2]` or `M.at(1,2)` – ar2015 Feb 12 '16 at 23:24
  • @ar2015 That's just how the library designers built it. You can't overload the `[]` operator in Javascript so they couldn't allow you to do `M[1][2]`. As for why they didn't give that method to the matrix "class", you'd have to ask them. – Mike Cluck Feb 12 '16 at 23:26
  • Is there any way that I add a patch function to the existing class? – ar2015 Feb 12 '16 at 23:28
  • 1
    @ar2015 If you can get access to the main matrix constructor, then you can extend it's prototype and add whatever you want. [I also found this hiding in their codebase](https://github.com/josdejong/mathjs/blob/1f000925b778c06ef8a0fd788deee840bcf78ea5/lib/type/matrix/Matrix.js#L126) that matrices may implement a `get` function. `M.get([1, 2])` but since I couldn't find strong docs on it, be wary. – Mike Cluck Feb 12 '16 at 23:34
  • 4
    I'm the author of math.js using math.index is indeed verbose, it's necessary because we can't overload JS operators. You can indeed safely use Matrix.get and Matrix.set to get/set individual values of a Matrix. We're currently working on documenting this, these matrix methods where missing in the docs. – Jos de Jong Feb 16 '16 at 11:49
  • @JosdeJong Was this ever included in the docs? Looking at the matrices doc page, it still only mentions subset/index method for this. I can't actually find an example usage of set but maybe its on a different page in the docs? – Joe Jankowiak Oct 12 '21 at 15:57
  • Good point, I don't see anything related in the docs either. Not sure why it wasn't addressed. Any help improving the docs would be welcome. – Jos de Jong Oct 14 '21 at 12:11
4

Apart from M.get([1, 2]), you can also do -

var a = M._data;    // a is a multidimensional array
console.log(a[1][2]);
Arik Pamnani
  • 421
  • 4
  • 7