I need to convert a 3 column array into a square matrix? - matrix

I am looking to convert my data to a square matrix:

Say your input is a list; you can then convert it to a list of lists (i.e., a proxy to a matrix) with list comprehension:
>>> x = [0, 5, 10, 5, 0, 2, 10, 2, 0]
>>> [x[3*k:3*k+3] for k in range(3)]
[[0, 5, 10], [5, 0, 2], [10, 2, 0]]
To help you parse the line: you are building a list by iterating over k from 0 to 2, where each element will be a slice of x that starts from index 3*k and ends at index 3*k+3. Thus, your list is [x[0:3], x[3:6], x[6:9]].
That said, it's much better to use numpy for all such needs. There, you would do:
>>> import numpy as np
>>> x = np.array([0, 5, 10, 5, 0, 2, 10, 2, 0])
>>> x.reshape(3, 3)
array([[ 0, 5, 10],
[ 5, 0, 2],
[10, 2, 0]])
The reshape() function converts your 1D array into the requested 2D matrix.

Related

how to speed up sympy-matrix of matrics calculation runtime

I've checked my code, there are no syntax error popping in the console, my matrix structures are correct, hence, mathematical operations are feasible.
if i run my code it takes forever, the console never get to print out the result. I broke the matrix to chokes of smaller code, its still taking time to compute.
from sympy import Symbol,Matrix
az = Matrix([[1, 2, 3, 4,5, 6],
[2, 3, 5, 6, 8, 6],
[4, 5, 6, 4, 8, 5],
[5, 6, 5, 8, 9, 9],
[4, 5, 6, 7, 8, 5],
[5, 6, 5, 8, 3, 9]])
fz = Matrix([[1,0,0,0,0,0],
[0,1,0,0,0,0],
[0,0,1,0,0,0],
[0,0,0,1,0,0],
[0,0,0,0,1,0],
[0,0,0,0,0,1]])
aa = Symbol('aa')
ff = Symbol('ff')
gen = Matrix([[aa, ff, 0, 0, 0, 0],
[ff,aa,ff,0,0,0],
[0,ff,aa,ff,0,0],
[0,0,ff,aa,ff,0],
[0,0,0,ff,aa,ff],
[0,0,0,0,ff,aa]])
inverse_genn = gen**-1
bz = Matrix([[2],
[3],
[3],
[4],
[5],
[5]])
bzz = Matrix([[bz],[bz],[bz],[bz],[bz],[bz]])
solution = inverse_genn*bzz
_1st_displacement = solution[0][0]
_1st_solution = _1st_displacement.subs({aa:az,ff:fz})
print('type',solution[0].shape)
print('solution',solution[0][0])
print('##'*100)
print('displacement matrix', _1st_solution)
Try make it easier to compute. Although an expression may be correct, it is not necessarily efficient for computation.
>>> eq=solution[0][0]
>>> count_ops(eq)
426
>>> s=eq.simplify()
>>> count_ops(s)
10
>>> s
2*(aa**2 - 1)/(aa**3 + aa**2 - 2*aa - 1)
>>> numer(s)/horner(denom(s))
(2*aa**2 - 2)/(aa*(aa*(aa + 1) - 2) - 1)
>>> h = _
>>> from time import time
>>> t=time(); e = h.subs(aa, az);print(time()-t)
0.0860941410065
Since horner does not apply itself to the numerator and denominator automatically, you have to use as_numer_denom to break up your simplified expression. Then you have to rebuild the expression. All together it looks like:
>>> be = zip(solution[0][0].simplify().as_numer_denom(), (1, -1))
>>> _1st_displacement = Mul(*[horner(b)**e for b,e in be])
CAUTION: this was written for an older version of SymPy. See comments below for modifications needed for newer SymPy.

Random's randint won't work in a for-loop

I'm trying to create a list with random length filled with lists of random lengths by using this code:
import random
solitaire = [None]*(random.randint(1,5))
for pile in solitaire:
number = random.randint(0, 10)
solitaire.append(number)
print(solitaire)
Easy enough I thought but when I ran this code my powershell window froze as it was expecting an input or something, I had to cancel the script with ctr+c and then got the message:
Traceback (most recent call last):
File "sparakod.py", line 254, in <module>
number = random.randint(0, 10)
File "C:\Python34\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Python34\lib\random.py", line 170, in randrange
def randrange(self, start, stop=None, step=1, _int=int):
KeyboardInterrupt
What does this mean? Why won't the code run?
number = random.randint(0, 10)
Seems to work just fine so why won't it inside the for-loop?
you don't say anything about the content of the lists, supposing that they also contain random integers, then a possible solution could be the following:
"""
It creates a list with random length filled with lists of random lengths containing random integers
"""
import random
MIN_LIST_OF_LISTS_LENGTH = 1
MAX_LIST_OF_LISTS_LENGTH = 10
MIN_LIST_LENGTH = 1
MAX_LIST_LENGTH = 5
MIN_LIST_ELEMENT = 1
MAX_LIST_ELEMENT = 10
#This is the list which will containt all the lists
solitaire = list(range(random.randint(MIN_LIST_OF_LISTS_LENGTH,MAX_LIST_OF_LISTS_LENGTH)))
for i, pile in enumerate(solitaire):
solitaire[i] = [
random.randint(MIN_LIST_ELEMENT, MAX_LIST_ELEMENT) for x in
range(0, random.randint(MIN_LIST_LENGTH, MAX_LIST_LENGTH))
]
print(repr(solitaire))
It will generate outputs like these:
[[10, 3], [5, 2, 7, 7, 6], [5], [9, 3, 2, 6], [2, 4, 4], [4, 5, 10, 9, 10]]
or
[[5, 1], [5, 1, 1], [1, 1, 7, 3, 1]]
or
[[9, 1, 6, 7], [10, 7, 1, 7, 4]]

How do I add columns and rows to a Matrix in Ruby?

If I have an existing Matrix in Ruby, how can I add a column or row of new data?
What I want to do is something like this:
require 'Matrix'
my_matrix = Matrix.diagonal(1,2,3)
my_matrix.append_row!([3,2,1])
my_matrix.append_column!([3,2,1])
Is there a way to do this?
Since doing this isn't (so far as I know) a valid matrix operation in the mathematical sense, there's nothing to do this in place. You can create a new Matrix though:
m = Matrix.diagonal(1, 2, 3)
#=> Matrix[[1, 0, 0], [0, 2, 0], [0, 0, 3]]
Matrix.columns(m.to_a << [4, 5, 6])
#=> Matrix[[1, 0, 0, 4], [0, 2, 0, 5], [0, 0, 3, 6]]
Matrix.rows(m.to_a << [4, 5, 6])
#=> Matrix[[1, 0, 0], [0, 2, 0], [0, 0, 3], [4, 5, 6]]
This uses columns or rows to create a new matrix by adding a new array
to the array representation of the original matrix.
I suspect the methods you are looking for are [hstack][1] and vstack.

how to get an order-specified subset of an array of variable length from an array of variable length?

I have an array of objects of variable length n. Defined by the number of records in my database.
I need a function to grab subsets (keeping the objects in order and always beginning at index 0) of the array of specified length m where m can be any integer I pass in.
e.g. if n = 10 and m = 4
array foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
subset a = [0, 1, 2, 3]
subset b = [4, 5, 6, 7]
subset c = [8, 9]
So, I need to programmatically be able to say, "Give me the i-th subset of length m from an array, given the array is length n." Using the previous example: "Give me the second subset of length four from foo" => returns the items at positions [4, 5, 6, 7].
I hope that made sense. Assistance with a ruby solution would be much appreciated! thx!
foo.each_slice(subset_length).to_a[subset_index]
e.g. foo.each_slice(4).to_a[2] returns "the second subset of length four from foo".
You can use Enumerable#each_slice:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(4).to_a
#=> [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]

Populate array from vector

I would like to populate an 2 dimensional array, from a vector.
I think the best way to explain myself is to put some examples (with a array of [3,5] length).
When vector is: [1, 0]
[
[4, 3, 2, 1, 0],
[4, 3, 2, 1, 0],
[4, 3, 2, 1, 0]
]
When vector is: [-1, 0]
[
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]
]
When vector is: [-2, 0]
[
[0, 0, 1, 1, 2],
[0, 0, 1, 1, 2],
[0, 0, 1, 1, 2]
]
When vector is: [1, 1]
[
[2, 2, 2, 1, 0],
[1, 1, 1, 1, 0],
[0, 0, 0, 0, 0]
]
When vector is: [0, 1]
[
[2, 2, 2, 2, 2],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0]
]
Have you got any ideas, a good library or a plan?
Any comments are welcome. Thanks.
Note: I consulted Ruby "Matrix" and "Vector" classes, but I don't see any way to use it in my way...
Edit: In fact, each value is the number of cells (from the current cell to the last cell) according to the given vector.
If we take the example where the vector is [-2, 0], with the value *1* (at array[2, 3]):
array = [
[<0>, <0>, <1>, <1>, <2>],
[<0>, <0>, <1>, <1>, <2>],
[<0>, <0>, <1>, *1*, <2>]
]
... we could think such as:
The vector [-2, 0] means that -2 is
for cols and 0 is for rows. So if we
are in array[2, 3], we can move 1 time
on the left (left because 2 is
negative) with 2 length (because
-2.abs == 2). And we don't move on the top or bottom, because of 0 for
rows.
It's quite easy to achieve this:
require 'matrix'
def build(rows, cols, vector)
Matrix.build(rows, cols){|i, j| vector.inner_product([cols-j-1, rows-i-1]) }
end
build(3, 5, Vector[1, 0]) # => your first example
# ...
build(3, 5, Vector[0, 1]) # => your last example
You will need the latest Matrix library which introduces Matrix.build.
Note: I find your examples a bit odd, and the third one even stranger. Looks like we have to divide by the vector you give, unless it's 0? Anyways, just adapt the block to the formula you need.
ok i am a little confused but i am going to take a shot in the dark
What you want is to run through every point in the array and call a function that would calculate the value at that position
so we have
loop i
loop j
array[i,j]=Vectorfunction(i,j,vector);
next j
next i
function(i,j,vector)
Here i am guessing you somehow use the position in the array, and the slope of the line defined by the vector. What that is i can't extract from the data, but i am sure such a function exists.
Most likely this involves arccos to get the angle. and then return i*arcsin+j+arccos

Resources