user2581724
user2581724

Reputation: 245

How do I create a negated matrix? (Python)

Let's say I have a matrix [[-2,4],[-6,8]].

I want to know how to get the opposite of those numbers: [[2,-4],[6,-8]].

Is there a special function in Python I'm supposed to use?

Upvotes: 1

Views: 2020

Answers (4)

skamsie
skamsie

Reputation: 2726

If you do not want to import packages and you also have a problem with list comprehensions but you like unnecessary complicated things you can use map() and lambda like this:

data = [[-2,4],[-6,8]]
reversed_data = map(lambda sublist: map(lambda x: -x, sublist), data)
# [[2, -4], [6, -8]]

EDIT: This example is working in python 2.7. In python 3+ map() returns an iterator so you need to do list(map()) to get this result. (credit goes to SethMMorton)

Upvotes: 0

user3494103
user3494103

Reputation:

import numpy

matrix = numpy.array([[-2,4],[-6,8]])
negatedMatrix = matrix * -1

print negatedMatrix

Giving the output:

[[ 2 -4]
 [ 6 -8]]

Upvotes: 0

shaktimaan
shaktimaan

Reputation: 12092

Using a list comprehension is one way to go about it:

>>> data = [[-2,4],[-6,8]]
>>> [[-ele for ele in item] for item in data]
[[2, -4], [6, -8]]

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114098

numpy is awesome :P

a = numpy.array( [[-2,4],[-6,8]])
a *= -1
print a

Upvotes: 3

Related Questions