Resizing matrix getting rid of 0 entries - Python
Question: I have my matrix `E`, which I have been filling in some way (it is not
important how, the important thing is that the entries are all different from
0). The dimension of the matrix is `n_x*n_y` X `n_x*n_y`, where

    
    
    n_x = 4
    n_y = 8
    

Now I set some of the entries to 0:

    
    
    step = 4.
    for i in range(n_x):
        for j in range(n_y):
            if ((i or j)%step != 0):
                e[i][j] = 0.
    

Then I want to get rid of the entries that are equal to 0., resizing my
matrix. The way I do that is:

    
    
    filter(lambda a: a != 0., E)
    

but what I get is

    
    
    filter(lambda a: a != 0., E)
    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
    

Can someone explain me what is happening and how to solve it?

EDIT:

I realised I made a mistake in my code, in the part where I am setting to 0
certain entries of my matrix. I will correct this in the following:

    
    
    step = 4.
        for i in range(n_x):
            for j in range(n_y):
                if ((i%step != 0) or (j%step !=0)):
                    e[i][j] = 0.
    


Answer: I've adapted and completed your code a little bit, and it's working fine (see
below).

I believe the problem you're seeing is that you are iterating over lists (1
dimension), rather than iterating over the items in the list (2 dimensions /
matrix).

You need to `map` your `filter` over the lists that make up your matrix.

    
    
    n_x = 4
    n_y = 8
    step = 4.
    
    e = [['x' for _ in range(n_y)] for _ in range(n_x)]
    
    # e:
    # [['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'],
    #  ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'],
    #  ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'],
    #  ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']]
    
    
    
    for i in range(n_x):
        for j in range(n_y):
            if ((i or j)%step != 0):
                e[i][j] = 0.
    
    # e: 
    # [['x', 0.0, 0.0, 0.0, 'x', 0.0, 0.0, 0.0],
    #  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    #  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    #  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
    
    
    # map + filter
    no_zeroes = list(map(lambda x: list(filter(lambda a: a != 0., x)), e))
    
    # no_zeroes:
    # [['x', 'x'], [], [], []]
    

In case a list comprehension is clearer, this is equivalent:

    
    
    # list comprehensions (equivalent)
    no_zeroes_lc = [[col for col in row if col != 0.] for row in e]
    
    # no_zeroes_lc:
    # [['x', 'x'], [], [], []]
    
    no_zeroes == no_zeroes_lc  # True
    

