Ester
Ester

Reputation: 23

How can I subtract the same array from all the columns of a matrix?

How can I subtract the same array from all the columns of a matrix ? I can't use for cycles.

For example I have w=([3,2],[4,3]) and v=(1,1) and I want w-v=([2,1],[3,2])

Upvotes: 2

Views: 42

Answers (3)

mad_
mad_

Reputation: 8273

Iterate and update the values of list w

for idx,tup in enumerate(zip(w,v)):
    for inner_idx,k in enumerate(tup[0]):
        w[idx][inner_idx]=k-tup[1]

print(w)#([2, 1], [3, 2])

Upvotes: 0

blhsing
blhsing

Reputation: 106455

You can use a generator expression like this:

tuple([a - b for a, b in zip(r, v)] for r in w)

This returns:

([2, 1], [3, 2])

Upvotes: 0

Xiaoyu Lu
Xiaoyu Lu

Reputation: 3570

Are you working in numpy?

It's as simple as

w = np.array([[3,2], [4,3]])
v = np.array([1,1])
result = w-v

This is a useful skill for numpy called broadcasting.

Upvotes: 1

Related Questions