How to create a 'matrix' of objects such as arrays/list in Ruby? -



How to create a 'matrix' of objects such as arrays/list in Ruby? -

i using ruby, , come matlab background. want create matrix of objects able perform matrix/mathematical style of indexing elements in matlab (mat(ii,jj) = some cell object). not see similar matrix type object in ruby.

what see best alternative create multidimensional array give construction of matrix, correct? how best create matrix construction in ruby? will row , column size defined initialization point , can changed afterwards?

currently, want insert other array objects in elements of matrix-like construction , do: (ar=array.new(3){array.new(3)})

irb(main):001:0> ar=array.new(3){array.new(3)} => [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]] irb(main):002:0> ar.size => 3 irb(main):004:0> ar[0].size => 3 irb(main):005:0> ar[0][0].size nomethoderror: undefined method `size' nil:nilclass (irb):5 :0 irb(main):006:0> ar[0][0]=[rand,rand,rand] => [0.327998120619301, 0.233951721107845, 0.0593579127810733] irb(main):007:0> ar[1][0]=[rand,rand,rand] => [0.698779972364559, 0.290838119763321, 0.41685249594095] irb(main):008:0> ar[2][0]=[rand,rand,rand]

and go on fill ^matrix^ way. there improve way this?

but there still problem cannot perform operations such as:

irb(main):026:0> ar[0][0] => [0.327998120619301, 0.233951721107845, 0.0593579127810733] irb(main):027:0> ar[0][1] => [0.360152144966612, 0.611276758393565, 0.0717397147786591] irb(main):028:0> ar[0][0]-ar[0][1] => [0.327998120619301, 0.233951721107845, 0.0593579127810733]

so way see individual indexing:

irb(main):032:0> ar[0][0][0]-ar[0][0][1] => 0.094046399511456

there matrix class:

require 'matrix' m = matrix[[0,1,0],[1,0,0],[0,1,1]] m.det #=> -1 m.diagonal? #=> false m.trace #=> 1

you can create random matrix with:

m = matrix.build(3,3) { rand }

note: matrix able serve 2d matrices, if need more dimensions, need build yourself.

ruby arrays matrix irb

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -