Python help involving matrix

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)

Hi,

after reviewing your script, the following two lines should not be indented:

    result = find_twos_or_nearest(combined_horizontal)
    print(result)

As they are written, they are part of the function. However, the return keyword statement ensures that they are never executed. So, unindent them.

Sorry I don’t really understand what you mean. I have removed the return np.array(result) but nothing works

Can you help me edit the code?

Look at the last two lines in the following script (your script but with the last two lines not part of the function). Notice how they have been unindented.

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)