Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limited matrices in Ruby

Tags:

ruby

matrix

How come the Matrix class has no methods to edit its vectors and components? It seems like everything inside a matrix can be read but not written. Am I mistaken? Is there some third-party elegant Matrix-like class that would allow me to delete rows and intentionally edit them?

Please, notify me if there is no such class – I will stop searching.

like image 530
gmile Avatar asked Sep 28 '09 11:09

gmile


People also ask

How do you add a matrix in Ruby?

The + is an inbuilt method in Ruby returns a matrix which has the addition of two matrix mat1 and mat2. Parameters: The function need two matrix mat1 and mat2 which are to be added. Return Value: It returns the resultant matrix after addition.

What is Ruby Matrix?

Ruby | Matrix [] method The []() is an inbuilt method in Ruby returns the element at the i-th row and the j-th column. Syntax: mat1[i, j]


1 Answers

The designer of class Matrix must have been a fan of immutable data structures and functional programming. Yes, you are correct.

In any case, there is a simple solution for what you want. Use Matrix for what it can do, then, just use .to_a to get a real array.

>> Matrix.identity(2).to_a
=> [[1, 0], [0, 1]]

See also Numerical Ruby Narray. You could also monkeypatch the class to add more behavior. If you do this, please patch a subclass of Matrix. (There are Ruby library projects out there that want more behavior from required classes so they directly modify them, making their new files somewhat toxic. They could have so easily just patched a subclass or singleton class.)

Oh, and khelll (:-) would probably like me to say that there is quite possibly a way for you to do what you want in a functional style. That is, by creating new objects rather than by modifying the old ones.

like image 103
DigitalRoss Avatar answered Sep 30 '22 13:09

DigitalRoss