Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy multiplication of a matrix by an array of scalars without for loop

Let's say I have the following code:

# define a 3x3 array
A = np.array([[-2, 1, 1], [1,-2,1], [1,1,-2]])
# define a 1D array of scalars to multiply A with
test = np.arange(10)

for i in range(len(test)):
    matrix = scipy.linalg.expm(A*test[i])

I want to see if there is a way to do this multiplication without using a for loop. I am not trying to multiply the two arrays using matrix multiplication. I am treating the test array as a bank of scalar values that I want to multiply A with one by one. There has got to be some kind of sneaky numpy way of doing this. Any ideas?

like image 439
sjhaque14 Avatar asked Sep 15 '25 20:09

sjhaque14


1 Answers

Here's an answer to the question "how to scale a matrix by multiple scalars without a for-loop". This disregards the matrix exponentiation, since I don't think there's a way to do that without the for-loop, but the question doesn't seem to be asking about the exponentiation step.

You can use 3D arrays to use numpy's vectorized multiplication.

import numpy as np

A = np.array([[[-2, 1, 1], [1,-2,1], [1,1,-2]]])
test = np.arange(10).reshape(-1,1,1)

result = test*A
like image 111
abatea Avatar answered Sep 18 '25 10:09

abatea