Ruby - Vectors and Matrices

Introduction

A vector is an ordered set of elements where certain mathematical operations may be performed.

A matrix is a collection of rows and columns, and each row is itself a vector.

Matrices allow you to perform matrix manipulations, which is a subject beyond the scope of this book and is only likely to be of interest to mathematical programmers.

First, given two Matrix objects, m1 and m2, you can add the values of each corresponding cell in the matrices with the plus sign, like this: m3 = m1+m2.

You must import Matrix using a require directive in order to use it:

Demo

require "Matrix"    # This is essential! 
#  w w  w  . j av a 2 s. c  o  m
m1 = Matrix[ [1,2,3,4], 
            [5,6,7,8], 
            [9,10,11,12], 
            [13,14,15,16]  ] 

m2 = Matrix[ [10,20,30,40], 
            [50,60,70,80], 
            [90,100,110,120], 
            [130,140,150,160]  ] 

m3 = m1+m2 
p(m3)

Result

Related Topics