MOON
MOON

Reputation: 2801

Matrix manipulation in numpy

I wrote the code below:

import os
import csv
import numpy as np

ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) # These two lines give the 
path = os.path.join(ROOT_PATH, "0.dat")  # path to a file on my disk

with open(path, 'r') as f1:
    listme = csv.reader(f1, delimiter="\t") # I imported the file
    listme2 = list(listme) # I used this command to make a matrix in the next line
    m = np.matrix(listme2)
    m2 = np.delete(m,[1,2],1) # I deleted two columns to get a 2 by 2 matrix

print m + m # It cannot add these two matrix. It also cannot multiply them by np.dot(m,m)

I cannot add the matrix I defined to itself. Please read the comment in the code.

The error returned is:

TypeError: unsupported operand type(s) for +: 'matrix' and 'matrix' 

Upvotes: 0

Views: 408

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 34017

It's not the matter with + operator, it's because m is a matrix of strings but not numbers. convert listme2 to a list of numbers before you use it to get m if you are ordered to do it manually with list comprehension:

listme2=[map(float, line) for line in listme]

Or, when creating the matrix, specify the dtype:

m = np.matrix(listme2, dtype=float)

You can also use np.loadtxt or np.genfromtxt to get the 2D array directly without open and csv.reader. Read the docs yourself ;)

Upvotes: 4

Related Questions