Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.

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, 1],[5, 4, 1, 3]]

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