4

I'm working on a program that determines if lines intersect. I'm using matrices to do this. I understand all the math concepts, but I'm new to Python and NumPy.

I want to add my slope variables and yint variables to a new matrix. They are all floats. I can't seem to figure out the correct format for entering them. Here's an example:

import numpy as np

x = 2
y = 5
w = 9
z = 12

I understand that if I were to just be entering the raw numbers, it would look something like this:

matr = np.matrix('2 5; 9 12')

My goal, though, is to enter the variable names instead of the ints.

2 Answers 2

4

You can do:

M = np.matrix([[x, y], [w, z]])

# or
A = np.array([[x, y], [w, z]])

I included the array as well because I would suggest using arrays instead of of matrices. Though matrices seem like a good idea at first (or at least they did for me), imo you'll avoid a lot of headache by using arrays. Here's a comparison of the two that will help you decide which is right for you.

The only disadvantage of arrays that I can think of is that matrix multiply operations are not as pretty:

# With an array the matrix multiply like this
matrix_product = array.dot(vector)

# With a matrix it look like this
matrix_product = matrix * vector
Sign up to request clarification or add additional context in comments.

Comments

2

Can you just format the string like this?:

import numpy as np

x = 2
y = 5
w = 9
z = 12

matr = np.matrix('%s %s; %s %s' % (x, y, w, z)) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.