1

I want to do a calculation through a function, which is related to kx and ky. kx and ky are two 2D arrays. How can I use python to do this?

Thank you!!!

enter image description here

1
  • 1
    Any reason why you don't just loop over x and y and set your new matrix element to (kx[x][y]/(kx[x][y]**2 + ky[x][y] ** 2)) ? Commented Jan 15, 2020 at 23:16

1 Answer 1

1

The de-facto standard package to do array math in python is numpy. So install the numpy package and then you'd do

import numpy as np  ## Pretty much everyone imports numpy as np, so might as well.


def my_function(kx, ky):
    return kx / (kx**2 + ky**2)

kx = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
ky = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) # Well we could also just have said ky = kx.T for the transpose, I guess.

output = my_function(kx, ky)

Note that math operations on numpy arrays are typically applied element-wise, so kx**2 just squares each element of kx individually, which is what you want here. For matrix-multiplication type squaring you'd do something like kx.dot(kx).

I assume your arrays kx and ky are just random examples; otherwise, there's more efficient ways to generate them than writing them out like this.

Of course nothing is wrong with the other posted solutions that use plain python objects and for loops, but for larger arrays you can expect numpy to be much more efficient.

Sign up to request clarification or add additional context in comments.

4 Comments

Actually I need more complex arrays, such like a 7X7 array. The value in each rows are the same, [1,2,3,4,5,6,7] ,[1,2,3,4,5,6,7] ,[1,2,3,4,5,6,7] ,[1,2,3,4,5,6,7] ,[1,2,3,4,5,6,7] ,[1,2,3,4,5,6,7] ,[1,2,3,4,5,6,7]. Is there any function like np.linespace? So that I can set the start number, end number, and the space? linespace(start, stop, num)
And would it look like "1, 2, 3, 4, 5, 6, 7" row-wise for the first one and column-wise for the second one?
There's both linspace and arange. In this case you probably want arange(1, 8). And then there are helper functions that turn this 1d array into two 2d ones, such as meshgrid if I recall correctly
Understand~ Thank you very much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.