# Test for a valid entry in a matrix

I have a question of methodology. The following code work nicely:

def ratio_for_pivot(mat, var_ent):
return [mat[i][mat.ncols()-1]/mat[i][var_ent] for i in range(mat.nrows()-1)]


It takes a matrix mat and a column number var_ent of this matrix and does the division of terms in the same row and return a vector. But as you can see, mat[i][var_ent] coud be 0. So I need a test. Should I construct a test function or is it possible to make directly a test (?) inside the list construction. For instance, this works as expected :

def pos_rat(x,y) :
if y>0:
return x/y
else :
return "NAN"
def ratio_for_pivot(mat, var_ent):
return [pos_rat(mat[i][mat.ncols()-1],mat[i][var_ent]) for i in range(mat.nrows()-1)]


But what I want to know is that is there a more compact way to obtain the same result.

As an exemple : M=[[1, 2, 3, 4],[2, 3, 0, 1],[5, 4, 1, 3]]

PS : Sorry for the ugly title I have no inspiration.

edit retag close merge delete

Again we do not have a code that illustrates the situation. This doesn't matter here maybe, since the answer to the question that can be extracted from the sentence "But what I want to know is that is there a more compact way to obtain the same result." is simply: "Yes". First of all, define a matrix as a matrix, respecting both mathematics and sage. The above code constructs a matrix as a list of lists. This is not a matrix, just type type(M) to get <class 'list'>. Instead...

sage: matrix(QQ, M)
[1 2 3 4]
[2 3 0 1]
[5 4 1 3]


is a true matrix. We also have aids to get good pivots, for instance:

sage: A = matrix(QQ, M)
sage: A.pivots()
(0, 1, 2)
sage: A.pivot_rows()
(0, 1, 2)


Try A.pivots? to see the first drops of information on the method.