Skip to main content

Multiplication of two matrix in swift

matrix multiplication formula

Swift program for Multiplication of two matrix. Here more solutions.

import Foundation
/*
  Swift 4 program for
  Two matrix multiplication
*/
class Multiply
{
	// Display the element of given 2d matrix
	static func printRecord(_ matrix: [[Int]])
	{
		print("  --------------");
		// Assume  N x N Matrix size
		let row: Int = matrix.count;
		let col: Int = matrix[0].count;
		var i: Int = 0;
		// Iterate the row element
		while (i < row)
		{
			var j: Int = 0;
			// Iterate the column element
			while (j < col)
			{
				// Display element value
				print("  " + String(matrix[i][j]), terminator: "");
				j += 1;
			}
			// Add new line
			print();
			i += 1;
		}
		print();
	}
	static func multiplication(_ a: [[Int]], _ b: [[Int]])
	{
		// Get the size
		let row: Int = a.count;
		let col: Int = a[0].count;
		// This matrix are store the result of multiplication 
		var result: [
			[Int]
		] = Array(repeating: Array(repeating: 0, count: col), count: row);
		var i: Int = 0;
		while (i < row)
		{
			var j: Int = 0;
			while (j < col)
			{
				// Set the initial value of new matrix element
				result[i][j] = 0;
				var k: Int = 0;
				while (k < row)
				{
					// Multiply matrix A [i] row and [k] columns to 
					// the Matrix B [k] columns and [j] rows.
					result[i][j] += a[i][k] * b[k][j];
					k += 1;
				}
				j += 1;
			}
			i += 1;
		}
		print("  Matrix A");
		// Print element of matrix x
		Multiply.printRecord(a);
		print("  Matrix B");
		// Print element of matrix y
		Multiply.printRecord(b);
		print("  Matrix [(A) x (B)]");
		// Display resultant matrix
		Multiply.printRecord(result);
	}
	static func main()
	{
		// Define matrix A
		let a: [
			[Int]
		] = [
			[1, 2, 3],
			[6, 1, 2],
			[5, 4, 3]
		];
		// Define matrix B
		let b: [
			[Int]
		] = [
			[3, 1, 3],
			[1, 1, 2],
			[2, 2, 3]
		];
		Multiply.multiplication(a, b);
	}
}
Multiply.main();

Output

  Matrix A
  --------------
  1  2  3
  6  1  2
  5  4  3

  Matrix B
  --------------
  3  1  3
  1  1  2
  2  2  3

  Matrix [(A) x (B)]
  --------------
  11  9  16
  23  11  26
  25  15  32




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment