Solution
Since you asked for alternation, I thought of given a more generic answer with three types of alternation:
- alternating
row
- alternating
column you asked for this
- alternating
row and column (both): like a chess-board
I will use this dummy data in the subsequent examples: A, B, C
# dummy data
import numpy as np
angles = np.random.rand(5,4) * np.pi
A. Expected output: alternating row
[[tan, tan, tan, tan],
[cos, cos, cos, cos],
[tan, tan, tan, tan],
[cos, cos, cos, cos],
[tan, tan, tan, tan]]
Code:
# import numpy as np
a = np.zeros(angles.shape)
a[0::2, :] = np.tan(angles[0::2, :])
a[1::2, :] = np.cos(angles[1::2, :])
B. Expected output: alternating column
[[tan, cos, tan, cos],
[tan, cos, tan, cos],
[tan, cos, tan, cos],
[tan, cos, tan, cos],
[tan, cos, tan, cos]]
Code:
# import numpy as np
a = np.zeros(angles.shape)
a[:, 0::2] = np.tan(angles[:, 0::2])
a[:, 1::2] = np.cos(angles[:, 1::2])
C. Expected output: alternating row and column
[[tan, cos, tan, cos],
[cos, tan, cos, tan],
[tan, cos, tan, cos],
[cos, tan, cos, tan],
[tan, cos, tan, cos]]
Code:
# import numpy as np
a = np.zeros(angles.shape)
a[0::2, 0::2] = np.tan(angles([0::2, 0::2])) # tan: odd-row, odd-column
a[0::2, 1::2] = np.cos(angles([0::2, 1::2])) # cos: odd-row, even-column
a[1::2, 0::2] = np.cos(angles([1::2, 0::2])) # cos: even-row, odd-column
a[1::2, 1::2] = np.tan(angles([1::2, 1::2])) # tan: even-row, even-column
D. Benefit of using numpy vectorization for alternating rows
You can use the following custom-defined function: custom_trig_func(). Applying numpy functions to numpy arrays are faster if you can skip for loops. The more vectorized your code is, the quicker it will run. The approach here avoids using for loops and uses in-built vectorization of numpy.tan and numpy.cos.
custom_trig_func(angles)
However, if you just want the minimal lines of code to produce what the custom function does, use this:
# angles is your input ndarray
even_rows = (np.arange(angles.shape[0]) % 2 == 0)
out = np.tan(angles)
out[even_rows, :] = np.cos(angles[even_rows, :])
print(out.shape) # out is your expected output
Code
import numpy as np
def custom_trig_func(angles: np.ndarray, validate=False) -> np.ndarray:
"""Returns an array of type -> numpy.ndarray and shape -> angles.shape, with
- odd rows operated on by numpy.tan() and,
- even rows operated on by numpy.cos().
"""
# determine odd and even row indices
rows = np.arange(angles.shape[0])
even_rows = (rows % 2 == 0)
odd_rows = ~even_rows
# create output array
out = np.tan(angles)
out[even_rows, :] = np.cos(angles[even_rows, :])
if validate:
assert np.all(out[odd_rows, :] == np.tan(angles[odd_rows, :])), "Validation error in applying TAN to odd rows"
assert np.all(out[even_rows, :] == np.cos(angles[even_rows, :])), "Validation error in applying COS to even rows"
return out
# dummy data
angles = np.random.rand(10,5) * np.pi
# apply custom function
custom_trig_func(angles=angles, validate=True)