Basically I want to present an algorithim which combines two different matrix into one. In the combined matrix, each column will have different values and there is always a ‘2’ in it. I want to extract it out and form a new matrix which only contains one row and the final results is like (2,2,2,2,2,…,2). However, I also want to add a code that if 2 is not find in the column, please extract the nearest value which is smaller than 2 out in each column.
I don’t know what’s wrong with my code
import numpy as np
matrix_A = np.array([[0.1],[1],[2],[3]])
matrix_B = np.array([[0.4,0.5,2,0.3,2,0.4], [1.2,1.1,2.5,2,2.5,1.4], [2,1.5,2.8,2.4,3,2], [3.5,2,4,5,6,2.1]])
#combine the two matrix
combined_horizontal = np.hstack((matrix_A, matrix_B))
#extract charging time
def find_twos_or_nearest(combined_horizontal):
result = []
for col in combined_horizontal.T: # Transpose the matrix to iterate over columns
if 2 in col:
result.append(2)
else:
# Find the maximum value less than 2
nearest = col[col < 2].max() if np.any(col < 2) else np.nan
result.append(nearest)
return np.array(result)
result = find_twos_or_nearest(combined_horizontal)
print(result)