Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to multiply two matrices in Swift

1 Answer

0 votes
import Foundation

func dotProduct(matrix1: [[Double]], matrix2: [[Double]]) -> [[Double]]? {
    let rows1 = matrix1.count
    let cols1 = matrix1[0].count
    let cols2 = matrix2[0].count
    
    var result = Array(repeating: Array(repeating: 0.0, count: cols2), count: rows1)
    
    for i in 0..<rows1 {
        for j in 0..<cols2 {
            for k in 0..<cols1 {
                result[i][j] += matrix1[i][k] * matrix2[k][j]
            }
        }
    }
    
    return result
}

let matrix1: [[Double]] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

let matrix2: [[Double]] = [
    [4, 6],
    [7, 3],
    [1, 2]
]

if let result = dotProduct(matrix1: matrix1, matrix2: matrix2) {
    for row in result {
        print(row)
    }
}



/*
run:
     
[21.0, 18.0]
[57.0, 51.0]
[93.0, 84.0]
     
*/
 

 



answered Mar 4, 2025 by avibootz
...