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,939 questions

51,876 answers

573 users

How to multiply two matrices in Go

1 Answer

0 votes
package main

import (
	"fmt"
)

func multiplyMatrices(A, B [][]int) [][]int {
	rowsA, colsA := len(A), len(A[0])
	rowsB, colsB := len(B), len(B[0])

	if colsA != rowsB {
		fmt.Println("Matrix multiplication is not valid.")
		return nil
	}

	// Initialize result matrix 
	result := make([][]int, rowsA)
	for i := range result {
		result[i] = make([]int, colsB)
	}

	// Perform multiplication
	for i := 0; i < rowsA; i++ {
		for j := 0; j < colsB; j++ {
			for k := 0; k < colsA; k++ {
				result[i][j] += A[i][k] * B[k][j]
			}
		}
	}

	return result
}

func printMatrix(matrix [][]int) {
	for _, row := range matrix {
		fmt.Println(row)
	}
}

func main() {
	// Define matrices A and B
	A := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
	B := [][]int{{4, 6}, {7, 3}, {1, 2}}

	result := multiplyMatrices(A, B)

	if result != nil {
		fmt.Println("Matrix A:")
		printMatrix(A)
		
		fmt.Println("Matrix B:")
		printMatrix(B)
		
		fmt.Println("Result: Matrix A * Matrix B:")
		printMatrix(result)
	}
}



/*
run:
     
Matrix A:
[1 2 3]
[4 5 6]
[7 8 9]
Matrix B:
[4 6]
[7 3]
[1 2]
Result: Matrix A * Matrix B:
[21 18]
[57 51]
[93 84]

*/
 

 



answered Mar 4, 2025 by avibootz

Related questions

1 answer 89 views
1 answer 92 views
92 views asked Mar 4, 2025 by avibootz
1 answer 69 views
1 answer 62 views
62 views asked Mar 4, 2025 by avibootz
...