Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Applying function to 2 vectors to obtain a 2D matrix

My question is exactly the same as this one but in Python instead of R. I couldn’t find a similar question for python and so I’m asking this one.

I have 2 vectors (lists actually)

a = [1,2,3]
b = [5,6,7]

A defined function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def calc(i, j):
    return (i+j)/2

I want to apply the calc function to all the pairs of values in the vectors so that i obtain a matrix (preferably using numpy package).

The expected result in this case is

result = [
           [3,   3.5,   4],
           [3.5,  4,  4.5], 
           [4,   4.5,   5]
         ]

I would like to avoid list comprehensions and for loops to achieve this result.

>Solution :

You can use meshgrid

import numpy as np

a = [1, 2, 3]
b = [5, 6, 7]

def calc(i, j):
    return (i + j) / 2

A, B = np.meshgrid(a, b)

result = calc(A, B)

print(result)

output:

[[3.  3.5 4. ]
 [3.5 4.  4.5]
 [4.  4.5 5. ]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading