I´m trying to multiply each row of array A by each of all the rows in another array (B) in order to get len(A) number of arrays with same number of rows and columns as the first two arrays.
Any help?
pseudo-code
from numpy import *
import numpy as np
def multipar():
A = array( [ (0.1,0.5,0.2,0.2), (0.2,0.5,0.1,0.2), (0.7,0.1,0.1,0.1) ] )
B = array( [ (1,2,3,4), (2,3,4,5), (3,4,5,6) ] )
for i in len(A):
average = A[i]*B
print average
multipar()
I would like to have each resulting new array
Array C
(0.1,0.5,0.2,0.2) * (1,2,3,4);
(0.1,0.5,0.2,0.2) * (2,3,4,5);
(...)
Array D
(0.2,0.5,0.1,0.2) * (1,2,3,4);
(...)
You could do something interesting with higher dimensions. Extend either A
or B
into the third dimension, then multiply that with the one that wasn't extended. eg:
A = array( [ (0.1,0.5,0.2,0.2), (0.2,0.5,0.1,0.2), (0.7,0.1,0.1,0.1) ] )
B = array( [ (1,2,3,4), (2,3,4,5), (3,4,5,6) ] )
tiled = tile (B, (3,1,1)).swapaxes (0,1)
all_results = A*tiled
Now you have all of your result arrays in all_results
; you can easily get them with all_results[0]
, all_results[1]
, etc
EDIT: In response to the latest question edit: If you really need the result arrays separately, then there are two further options:
C, D, E = all_results
replace the last two statements in my first suggestion with:
C = B * A[0]
D = B * A[1]
E = B * A[2]
If you really need separate arrays for the results, and with many more rows so that a loop becomes necessary, then you can do something like (thanks @Jaime for the broadcasting notation)
all_results = A[:, None, :] * B[None, :, :]
for i, res in enumerate (all_results):
locals () ['result%d'%i] = res
Now the result of multiplying by the first row is in the variable called res1
, the second row in res2
, and so forth.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.