Trong bài viết này, chúng ta sẽ tìm hiểu về các ma trận trong Python bằng cách sử dụng nested list (danh sách lồng ghép) và thư viện NumPy.

Ma trận là cấu trúc dữ liệu hai chiều, trong đó các số được sắp xếp thành các hàng và cột. Ví dụ:

Đây là ma trận 3×4 vì nó có 3 hàng và 4 cột.

Ma trận trong Python

Python không có kiểu xây dựng riêng dành cho ma trận, vậy nên chúng ta có thể biểu diễn ma trận dưới dạng một nested list.

Vậy nested list là gì?

Nested list là dạng danh sách lồng ghép, nghĩa là một list xuất hiện với vai trò là phần tử của một list khác. Ví dụ:

A = [ 1, 4, 5, [8, 9]]

Ở ví dụ này, nếu in ra A[3] ta được output là [8, 9].

Nested list thường được dùng để trình bày ma trận trong Python. Biểu diễn như sau:

A = [[1, 4, 5], 
    [-5, 8, 9]]

Chúng ta có thể coi danh sách này là một ma trận gồm 2 hàng và 3 cột.

Để kết xuất phần tử từ ma trận, ta có thể chọn cả một hàng của ma trận theo cách thông thường hoặc dùng dạng chỉ số kép, chỉ số thứ nhất để chọn hàng, còn chỉ số thứ hai chọn cột. Cùng xem ví dụ sau:

A = [[1, 4, 5, 12], 
 [-5, 8, 9, 0],
 [-6, 7, 11, 19]]

print("A =", A) 
print("A[1] =", A[1]) # Hàng thứ 2 của ma trân
print("A[1][2] =", A[1][2]) # Phần tử thứ 3 của hàng thứ 2
print("A[0][-1] =", A[0][-1]) # Phần tử cuối cùng của hàng 1

column = []; 
for row in A:
 column.append(row[2])

print("Cột thứ 3 =", column)

Chạy chương trình, output được trả về là:

A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]
A[1] = [-5, 8, 9, 0]
A[1][2] = 9
A[0][-1] = 12
Ct th 3 = [5, 9, 11]

Dùng nested list để biểu diễn ma trận là một cách thông dụng và thường dùng trong các tính toán đơn giản. Tuy nhiên có một cách hay hơn đó là sử dụng thư viện NumPy.

Sử dụng NumPy cho ma trận

NumPy là thư viện được viết bằng Python nhằm phục vụ cho việc tính toán khoa học, hỗ trợ nhiều kiểu dữ liệu đa chiều giúp cho việc tính toán, lập trình, làm việc với các hệ cơ sở dữ liệu cực kì thuận tiện.

Để tạo một ma trận ta có thể sử dụng ndarray (viết gọn là array) của NumPy

Array này là một đối tượng mảng đa chiều thuần nhất tức là mọi phần tử đều cùng 1 kiểu.

Hãy thử với một ví dụ:

import numpy as np
a = np.array([1, 2, 3])
print(a) 

# Output: [1, 2, 3]

print(type(a)) 

# Output: <class 'numpy.ndarray'>

Cách tạo array của NumPy

Mảng số nguyên, số thực, số phức (integer, float, complex)

import numpy as np

A = np.array([[1, 2, 3], [3, 4, 5]])
print(A)

A = np.array([[1.1, 2, 3], [3, 4, 5]]) # mảng số thực
print(A)

A = np.array([[1, 2, 3], [3, 4, 5]], dtype = complex) # mảng số phức
print(A)

Chương trình trả về kết quả:

[[1 2 3]
 [3 4 5]]

[[1.1 2. 3. ]
 [3. 4. 5. ]]

[[1.+0.j 2.+0.j 3.+0.j]
 [3.+0.j 4.+0.j 5.+0.j]]

Mảng giá trị mặc định (0 và 1)

import numpy as np

# Mọi phần tử đều là 0
A = np.zeros( (2, 3) )
print(A)

# Output:
 [[0. 0. 0.]
 [0. 0. 0.]]

# Mọi phần tử đều là 1
B = np.ones( (1, 5) )
print(B)

# Output: [[1 1 1 1 1]]

Sử dụng arange() và shape()

import numpy as np

A = np.arange(4)
print('A =', A)

B = np.arange(12).reshape(2, 6)
print('B =', B)

# Output:
A = [0 1 2 3]
B = [[ 0 1 2 3 4 5]
 [ 6 7 8 9 10 11]]

Các phép toán với ma trận

Các phép toán trên ma trận là những tính toán cơ bản khi làm việc. Trong phần này, Quantrimang chỉ đề cập tới 3 phép toán cơ bản thường được sử dụng là cộng ma trận, nhân ma trận và chuyển vị ma trận.

Các phép toán ở đây sử dụng cả nested list và thư viện NumPy.

Cộng 2 ma trận

Để cộng hai ma trận, ta cộng từng phần tử tương ứng của 2 ma trận cùng cấp với nhau.

import numpy as np

A = np.array([[2, 4], [5, -6]])
B = np.array([[9, -3], [3, 6]])
C = A + B 
print(C)

''' 
Output:
[[11 1]
 [ 8 0]]
 '''

Nhân 2 ma trận

Nhân 2 ma trận là phép lấy tổng của tích từng phần tử của hàng tương ứng với cột tương ứng.

Chú ý: Nhân ma trận chỉ xảy ra khi số cột của ma trận A bằng với số hàng của ma trận B. Ví dụ cho 2 ma trận [A]mp và [B]pn, tích chúng theo thứ tự đó sẽ được kết quả là ma trận [AB]mn.

Biểu diễn với NumPy như sau:

import numpy as np

A = np.array([[3, 6, 7], [5, -3, 0]])
B = np.array([[1, 1], [2, 1], [3, -3]])
C = a.dot(B)
print(C)

# Output:
[[ 36 -12]
 [ -1 2]]

Chuyển vị ma trận

Chuyển vị là phép biến cột thành hàng và hàng thành cột của một ma trận.

import numpy as np

A = np.array([[1, 1], [2, 1], [3, -3]])
print(A.transpose())

#Output:
[[ 1 2 3]
 [ 1 1 -3]]

Xuất các phần tử, cột, dòng của ma trận

Xuất các phần tử của ma trận

Tương tự với cách kết xuất bằng list, chúng ta có thể sử dụng bằng NumPy. Trước tiên, hãy thử với mảng một chiều:

import numpy as np
A = np.array([12, 14, 16, 18, 20])

print("A[0] =", A[0]) # phần tử đầu tiên 
print("A[2] =", A[2]) # phần tử thứ 3
print("A[-1] =", A[-1]) # phần tử cuối cùng

Output được trả về ở đây là:

A[0] = 12
A[2] = 16
A[-1] = 20

Ví dụ về mảng hai chiều:

import numpy as np

A = np.array([[1, 4, 5, 12],
 [-5, 8, 9, 0],
 [-6, 7, 11, 19]])

# Phần tử đầu tiên của hàng đầu tiên
print("A[0][0] =", A[0][0])

# Phần tử thứ 3 của hàng thứ 2
print("A[1][2] =", A[1][2])

# Phần tử cuối cùng của hàng cuối cùng
print("A[-1][-1] =", A[-1][-1])

Chạy chương trình, kết quả được trả về là:

A[0][0] = 1
A[1][2] = 9
A[-1][-1] = 19

Xuất các dòng của ma trận

import numpy as np

A = np.array([[1, 4, 5, 12], 
 [-2, 8, 6, 14],
 [-1, 5, 10, 22]])

print("A[0] =", A[0]) # Dòng đầu tiên
print("A[2] =", A[2]) # Dòng thứ 3
print("A[-1] =", A[-1]) # Dòng cuối cùng (dòng thứ 3)

Output được trả về ở đây là:

A[0] = [1, 4, 5, 12]
A[2] = [-1, 5, 10, 22]
A[-1] = [-1, 5, 10, 22]

Xuất các cột của ma trận

import numpy as np

A = np.array([[1, 4, 5, 12], 
 [-2, 8, 6, 14],
 [-1, 5, 10, 22]])

print("A[:,0] =",A[:,0]) # Cột đầu tiên
print("A[:,3] =", A[:,3]) # Cột thứ 4
print("A[:,-1] =", A[:,-1]) # Cột cuối cùng (Cột thứ 4)

Output được trả về:

A[:,0] = [ 1 -2 -1]
A[:,3] = [12 14 22]
A[:,-1] = [12 14 22]

Lát cắt của Ma trận

Lát cắt của mảng một chiều trong NumPy được biểu diễn tương tự như list.

import numpy as np
A = np.array([1, 3, 5, 7, 9, 7, 5])

# Phần tử thứ tự từ 3 đến 5
print(A[2:5]) # Output: [5, 7, 9]

# Phần tử thứ tự từ 1 đến 4
print(A[:-5]) # Output: [1, 3]

# Phần tử thứ 6 trở đi
print(A[5:]) # Output:[7, 5]

# Lấy cả mảng
print(A[:]) # Output:[1, 3, 5, 7, 9, 7, 5]

# đổi chiều mảng
print(A[::-1]) # Output:[5, 7, 9, 7, 5, 3, 1]

Vậy để cắt ma trận, ta có ví dụ sau:

import numpy as np

A = np.array([[1, 4, 5, 12, 14], 
 [-5, 8, 9, 0, 17],
 [-6, 7, 11, 19, 21]])

print(A[:2, :4]) # 2 hàng, 4 cột

''' Output:
[[ 1 4 5 12]
 [-5 8 9 0]]
'''

print(A[:1,]) # hàng đầu tiên, tất cả cột

''' Output:
[[ 1 4 5 12 14]]
'''

print(A[:,2]) # tất cả các hàng, cột 2

''' Output:
[ 5 9 11]
'''

print(A[:, 2:5]) # tất cả các hàng, cột 3 đến 5

'''Output:
[[ 5 12 14]
 [ 9 0 17]
 [11 19 21]]
'''

Vậy như bạn thấy, sử dụng thư viện NumPy thay vì nested list làm cho các phép toán với ma trận dễ dàng hơn rất nhiều. Tin học của em khuyên bạn nên tìm hiểu và học cách sử dụng thư viện NumPy thật kĩ đặc biệt khi sử dụng Python để áp dụng cho việc tính toán khoa học hay phân tích dữ liệu.

37 BÌNH LUẬN

  1. หากคุณไม่มั่นใจในการเริ่มโปรเจ็คใหม่ของคุณ หรือต้องการทราบขอบเขตของงาน เราสามารถเป็นที่ปรึกษาในทุกข้อสงสัย และจะช่วยคุณตลอดการดำเนินงานของคุณ สามารถติดต่อเข้ามาพูดคุยกับเราก่อนได้

    You are employing a browser that isn’t supported by Fb, so we have redirected you to definitely
    a less complicated Variation to provde the very
    best working experience.

    รับกลยุทธ์การตลาดดิจิทัลที่ผ่านการพิสูจน์แล้ว จากทีมผู้เชี่ยวชาญของเราสู่การเพิ่มรายได้จากฝั่งออนไลน์ของคุณ

    หากคุณต้องการงานภาพกราฟิกดีไซน์ที่มีคุณภาพในขอนแก่น เราคือคำตอบการงานกราฟิกชั้นนำในขอนแก่น ที่มีรูปแบบดีไซน์ที่หลากหลายและเป็นสากล

    เยส เว็บ ดีไซน์ สตูดิโอ เป็นบริษัทที่รับออกแบบเว็บไซต์ ที่เชี่ยวชาญในการออกแบบเว็บไซต์และพัฒนาเว็บไซต์ให้กับลูกค้าที่ขอนแก่น เราคือบริษัททำเว็บไซต์หนึ่งเดียวในขอนแก่น ที่มีการออกแบบที่โดดเด่นไม่เหมือนใคร

    ติวเตอร์ และผู้เชี่ยวชาญที่ให้ความรู้เฉพาะด้าน

    วิธีการใช้งานสมัครเป็นฟรีแลนซ์เริ่มขายงานอย่างไรการชำระค่าจ้างรับประกันการจ้างงานบล็อกความรู้คำถามที่เจอบ่อย

    คุมงบได้เองมีผู้ช่วยดูแลจนจบงานตอบเร็วแน่นอนการันตีคุณภาพงาน

    เราดูแลลูกค้าด้วยการให้คำปรึกษาอย่างละเอียด
    และเมื่อเราเข้าใจเป้าหมายและข้อกำหนดของแบรนด์นั้นๆ แล้ว เราจะสามารถสร้างแคมเปญที่มีประสิทธิภาพ ซึ่งจะช่วยให้บริษัทของคุณเติบโตไปในทิศทางที่ดีที่สุด
    ไม่ว่าจะเป็นยอดการเข้าชมที่มากขึ้น คอนเวอร์ชั่นเรทที่สูงขึ้น การจัดอันดับที่ดีขึ้น หรือรายได้ที่มีนัยสำคัญยิ่งขึ้น ซึ่งเราจะทำการออกแบบกลยุทธ์เพื่อให้เหมาะกับกลุ่มลูกค้าและเป้าหมายของคุณมากที่สุด

    บริการทำการตลาดออนไลน์
    เพิ่มยอดขายสินค้า โดยทีมงานมืออาชีพ

    เยส เว็บ ดีไซน์ สตูดิโอ บริษัทรับออกแบบเว็บไซต์ขอนแก่น รับทำเว็บขอนแก่น

    social banking คืออะไร จะมาเปลี่ยนโลกอย่างไร

    เนื้อหาเว็บไซต์ อัพเดทเว็บไซต์ให้มีความเคลื่อนไหวอยู่เสมอ และมีการอัพเดตเนื้อหาที่น่าสนใจ และต้องเป็นไปในทิศทางเดียวกัน และเกี่ยวข้องกับ keyword phrases
    ที่ต้องการ

    ในฐานะการเป็นผู้นำทางด้านออกแบบ เราตั้งใจและหาวิธีทำให้ธุรกิจของคุณเป็นที่รู้จักกับลูกค้าและตรงต่อความต้องการ ต่อยอดธุรกิจ ขยายช่องทางการขาย และสร้างการรับรู้บนโลกออนไลน์

    It seems like you had been misusing this attribute by heading
    much too speedy. You’ve been temporarily blocked from using it.

    พวกเราจะสร้างธุรกิจของคุณที่ขอนแก่น
    ด้วยเว็บไซต์ที่มีคุณภาพสูงและอัตราการเข้าถึงที่มีประสิทธิภาพ

    You are using a browser that won’t supported by Fb, so we have redirected you to definitely a
    simpler Variation to give you the best working experience.

  2. Magnificent goods from you, man. I have understand your stuff previous to and you’re just too fantastic.
    I actually like what you have acquired here, really like what you are saying and
    the way in which you say it. You make it entertaining and you still take care of to keep it sensible.

    I can’t wait to read much more from you. This is really
    a terrific web site.

  3. I’m not sure why but this blog is loading
    extremely slow for me. Is anyone else having this issue or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

  4. I was extremely pleased to discover this site. I wanted to thank
    you for your time for this particularly wonderful read!!
    I definitely liked every part of it and i also have you saved as
    a favorite to check out new stuff on your site.

  5. I do not even know the way I ended up right here, but I thought this post was once great.
    I don’t recognise who you’re however definitely you’re going to a famous blogger should you
    are not already. Cheers!

  6. I was extremely pleased to find this great site.
    I want to to thank you for ones time just for this wonderful read!!
    I definitely appreciated every little bit of it and I
    have you book-marked to check out new things in your website.

  7. constantly i used to read smaller articles which also clear their motive, and that is also happening with this
    post which I am reading at this time.

  8. Hi there, I found your web site by means of
    Google at the same time as looking for a related subject, your
    website came up, it seems to be good. I’ve bookmarked it
    in my google bookmarks.
    Hello there, simply was alert to your blog via Google,
    and found that it’s really informative. I’m going to be careful
    for brussels. I will be grateful when you proceed this in future.

    Numerous other folks shall be benefited from
    your writing. Cheers!

  9. Hello There. I discovered your blog the use of msn. This is an extremely well written article.
    I will make sure to bookmark it and return to
    learn more of your helpful information. Thank you for the post.
    I’ll certainly return.

  10. We’re a gaggle of volunteers and opening a new scheme in our community.

    Your site offered us with valuable info to work on. You’ve
    performed an impressive activity and our whole
    group can be grateful to you.

  11. Nice post. I was checking constantly this blog and I am impressed!
    Very helpful information particularly the last part 🙂 I care for such information much.
    I was looking for this particular information for a very long time.
    Thank you and good luck.

  12. Spot on with this write-up, I seriously think this amazing site needs a great deal
    more attention. I’ll probably be back again to read through more, thanks for the info!

  13. My programmer is trying to persuade me to move to .net from PHP.

    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using Movable-type
    on a number of websites for about a year and am nervous about
    switching to another platform. I have heard very good things about blogengine.net.

    Is there a way I can import all my wordpress posts into it?
    Any help would be really appreciated!

  14. I’ve been exploring for a little for any high quality articles or weblog posts in this sort
    of space . Exploring in Yahoo I finally stumbled upon this web
    site. Studying this information So i am glad to exhibit that I’ve a very just right uncanny feeling I found out exactly what I needed.
    I such a lot certainly will make sure to don?t put out of your mind this web site and give it a look regularly.

  15. You actually make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand.
    It seems too complex and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  16. I have read some good stuff here. Definitely value bookmarking for
    revisiting. I surprise how much attempt you set to make this type
    of magnificent informative website.

  17. Having read this I thought it was very enlightening. I appreciate you taking the time and energy to
    put this informative article together. I once again find myself spending a lot of time both reading and commenting.
    But so what, it was still worth it!

  18. A person essentially assist to make seriously articles
    I would state. This is the very first time I frequented your web page and so far?
    I surprised with the research you made to create this particular publish extraordinary.

    Excellent process!

  19. Exceptional post but I was wondering if you could
    write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further.
    Thanks!

  20. Spot on with this write-up, I truly believe that this web site needs a great deal more attention. I’ll probably be returning to see more,
    thanks for the advice!

  21. My brother recommended I would possibly like this website.

    He was once entirely right. This post actually made my day.
    You cann’t imagine simply how a lot time I had spent for this information! Thanks!

  22. My spouse and I stumbled over here from a different web page and thought I might as well check things
    out. I like what I see so i am just following you. Look forward
    to going over your web page repeatedly.

  23. Hey there I am so happy I found your blog page, I really found you by error, while I was searching on Bing
    for something else, Anyways I am here now and would
    just like to say many thanks for a tremendous post and a all round interesting blog (I also love the
    theme/design), I don’t have time to look over it all
    at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read more, Please
    do keep up the fantastic job.

THOÁT KHỎI BÌNH LUẬN

Please enter your comment!
Please enter your name here