-2

I am trying to find a method to find the submatrix of an array X where the user provides an input i and j like so:

def submatrix(X, i, j):

The expected output should be the matrix X without row i and column j.

Example :

X = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

submatrix(X, 1, 1)

    [[1, 3],
     [7, 9]]

I have tried to solve it on my own but obviously have not managed to do it and dont know where to begin. Hence asking for help.

Raju
  • 25
  • 8
  • Have you written any code yet? Have you tried making a plan on paper? Any idea of where to start? – AMC Dec 12 '19 at 17:57
  • Welcome to StackOverflow. [On topic](https://stackoverflow.com/help/on-topic), [how to ask](https://stackoverflow.com/help/how-to-ask), and ... [the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is a knowledge base for *specific* programming problems -- not a design, coding, research, or tutorial resource. Show us your best attempts, things that can remove in each direction. – Prune Dec 12 '19 at 17:59
  • Does this answer your question? [Sub matrix of a list of lists (without numpy)](https://stackoverflow.com/questions/15650538/sub-matrix-of-a-list-of-lists-without-numpy) – Reznik Dec 12 '19 at 17:59

5 Answers5

1

Using for loop:

X = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

def submatrix(X, i, j):
    X=X[:]
    del(X[i]) # delete the row
    for n in range(len(X)):
        del(X[n][j])  # delete the column elements of the rows
    return X

X_new = submatrix(X, 1, 1)
[[1, 3], [7, 9]]
seralouk
  • 30,938
  • 9
  • 118
  • 133
0

How's this?

def submatrix(X, i, j):
    return [[elem for x, elem in enumerate(row) if x != i]
            for y, row in enumerate(X) if y != j]

X = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

print(submatrix(X, 1, 1))
Izaak van Dongen
  • 2,450
  • 13
  • 23
0
def submatrix(x, i, j):
    matrix = []
    for row in x[:i] + x[i+1:]:
        matrix.append(row[:j] + row[j+1:])
    return matrix

Examples

>>> submatrix([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]], 1, 1)
[[1, 3],
 [7, 9]]

>>> submatrix([[1, 2, 3, 4],
               [5, 6, 7, 8],
               [2, 4, 5, 9],
               [9, 6, 4, 3]], 2, 1)
[[1, 3, 4],
 [5, 7, 8],
 [9, 4, 3]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

Here is the solution. First you should remove the row and then iterate through all row rows to remove the column index of the nested list. Like this

def submatrix(X, i, j):
    del X[i]
    for k in range(len(X)):
        del X[k][j]
M Hamza Razzaq
  • 432
  • 2
  • 7
  • 15
0

This can work too:

def submatrix(X, i, j):
    X = X[:i] + X[i+1:] if i!= len(X) else X[:-1]
    X = [i[:j] + i[j+1:] if j!= len(X[0]) else i[:-1] for i in X]
    return X
Vicrobot
  • 3,795
  • 1
  • 17
  • 31