Zeroing A Matrix

February 17, 2017

Our solution first scans for zero elements, then goes back and makes changes. The rows and columns that need to be zeroed are collected in sets rows and cols, which are lists to which duplicate elements are not added:

(define (adjoin x xs)
  (if (member x xs) xs
    (cons x xs)))
(define (zero mtrx)
  (let ((rows (list)) (cols (list))
        (n-rows (matrix-rows mtrx))
        (n-cols (matrix-cols mtrx)))
    (for (row 0 n-rows)
      (for (col 0 n-cols)
        (when (zero? (matrix-ref mtrx row col))
          (set! rows (adjoin row rows))
          (set! cols (adjoin col cols)))))
    (do ((rows rows (cdr rows))) ((null? rows))
      (for (col 0 n-cols)
        (matrix-set! mtrx (car rows) col 0)))
    (do ((cols cols (cdr cols))) ((null? cols))
      (for (row 0 n-rows)
        (matrix-set! mtrx row (car cols) 0)))
    mtrx))

Here’s an example:

> (zero '#(#(0 2 3 4 5)
                    #(1 0 3 4 5)
                    #(1 2 0 4 5)
                    #(1 2 3 0 5)
                    #(1 2 3 4 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))

You can run the program at http://ideone.com/X7roST.

Advertisement

Pages: 1 2

2 Responses to “Zeroing A Matrix”

  1. Paul said

    In Python using numpy.

    import numpy as np
    def zero(matrix):
        rows, cols = [list(set(x)) for x in np.where(matrix == 0)]
        matrix[rows, :] = 0
        matrix[:, cols] = 0
    
  2. r. clayton said

    A solution in Racket.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: