[Tutor] Python 3.6 Multiply the elements of a 2D Array by the elements of a 1D Aeeay

Steven D'Aprano steve at pearwood.info
Thu Apr 13 20:42:55 EDT 2017


On Thu, Apr 13, 2017 at 03:41:09PM -0400, Stephen P. Molnar wrote:

> I have an list generated by:   s = np.linspace(start,finish,points)
> 
> and an array D:
> 
>  [ 0.          2.059801    3.60937686  3.32591826  2.81569212]
>  [ 2.059801    0.          4.71452879  4.45776445  4.00467382]
>  [ 3.60937686  4.71452879  0.          5.66500917  5.26602175]
>  [ 3.32591826  4.45776445  5.66500917  0.          5.02324896]
>  [ 2.81569212  4.00467382  5.26602175  5.02324896  0.        ]

Some advice for when you ask for help: we're volunteers, not paid to 
work on your problem, so the easier you make it for us, the more likely 
you will get a good answer.

Start off by simplifying the problem. Do you really need a 5x5 array 
with so many decimal places just to ask the question? Probably not. A 
2x2 array will probably demonstrate the question just as well, and be 
MUCH easier for us to read and type.

What code did you use to create D? It is better to show us that rather 
than just the output of what D looks like. I've tried various things, 
and I cannot duplicate the output that you show. That means I cannot 
tell if I'm working with the same data type as you.

My *guess* is that you did something like this to get D:

py> D = np.array([[1.5, 2.5], [3.5, 4.5]])
py> print D
[[ 1.5  2.5]
 [ 3.5  4.5]]

but I can't be sure, and of course I have no idea what the mystery list 
"s" contains, because you don't tell us. So I'm working in the dark.


> However, what I want to do is multiply each element ob D by each element 
> of s and sum all of the products.

Can you give us an example? This is ambiguous, it could mean either of 
*at least* two things.

(1) Take each element of D in turn, and multiply by the corresponding 
element of s. Here is an example:

D = [[ 1  2 ]
     [ 3  4 ]]

s = [10 20 30 40]

So you want:

1*10 + 2*20 + 3*30 + 4*40


(2) Take each element of D in turn, and multiply by each of the elements 
of s. Using the same examples for D and s:

( 1*10 + 1*20 + 1*30 + 1*40 + 
  2*10 + 2*20 + 2*30 + 2*40 + 
  3*10 + 3*20 + 3*30 + 3*40 + 
  4*10 + 4*20 + 4*30 + 4*40 )


Which do you want?

Remember, the better the question you ask, the better the answers we can 
give.



-- 
Steve


More information about the Tutor mailing list