Python Forum

Full Version: How to replace column of a Matrix
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am wondering how to replace column of one matrix with another matrix column. Here is my code.

import random
import numpy as np
import matplotlib    
import matplotlib.pyplot as plt

# Matrix 
A = [[1, 2, 3, 4], 
    [5, 6, 7, 8],
    [9, 10, 11, 12]]

B = [[0, 0, 0, 0], 
    [0, 0, 0, 0],
    [0, 0, 0, 0]]

# Elements of Matrix 
print("Matrix A =", A) 
print("1nd row " + " A[0] = ", A[0])
print("2nd row " + " A[1] = ", A[1])
print("3rd row " + " A[2] = ", A[2])
print("3rd element of 2nd row " + " A[1][2] = ", A[1][2])   
print("Last element of 1st Row" + " A[0][-1] = ", A[0][-1])   

# Replacing Rows  
B[0] = A[0]
print("Matrix A =", A)
print("Matrix B =", B)
 
# Replacing Cols  
B[:,[0]] = A[:,[0]] 
print("Matrix A =", A)
print("Matrix B =", B)
I get this error " B[:,[0]] = A[:,[0]]
TypeError: list indices must be integers or slices, not tuple"
# Replacing Cols  
for row_b, row_a in zip(B, A):
    row_b[0] = row_a[0]
Yes, it works but I don't understand the code. what is this zip function.
https://docs.python.org/3/library/functions.html#zip Wrote:zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks.

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead.

zip() in conjunction with the * operator can be used to unzip a list:
(Aug-22-2021, 10:11 AM)Joni_Engr Wrote: [ -> ]Yes, it works but I don't understand the code. what is this zip function.
Now I get it. Thanks.