Write a program to multiply two matrices.
Example:
Input:arr[3][3]={{6,2,3},{4,3,2},{4,5,7}},brr[3][3]={{4,6,2},{2,6,1},{1,5,1}}
Output:arr[3][3]={{31,63,17},{24,52,13},{33,89,20}}
Approach
C
#include <stdio.h>//function to multiply two maytricesvoid multiplyMatrix(int arr[][3], int brr[][3], int n){//matrix which store the resultint crr[3][3];for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){crr[i][j] = 0;for (int k = 0; k < n; k++){crr[i][j] += arr[i][k] * brr[k][j];}}}//store the final result back to//arrfor (int i = 0; i < n; i++){for (int j = 0; j < n; j++)arr[i][j] = crr[i][j];}}int main(){//first matrix 3 X 3 matrixint arr[][3] = {{6, 2, 3}, {4, 3, 2}, {4, 5, 7}};//second matrix 3 X 3int brr[][3] = {{4, 6, 2}, {2, 6, 1}, {1, 5, 1}};int n = 3;multiplyMatrix(arr, brr, n);printf("Result after multiply is\n");for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){printf("%d ", arr[i][j]);}printf("\n");}return 0;}//Time Complexity: O(n^3)//Space Complexity:O(n^2)
Java
public class MatrixMultiplication {public static void main(String[] args) {int matrixA[][] = { { 6, 2, 3 }, { 4, 3, 2 }, { 4, 5, 7 } };int matrixB[][] = { { 4, 6, 2 }, { 2, 6, 1 }, { 1, 5, 1 } };int maxtriMul[][] = matrixMultiplication(matrixA, matrixB);printMatrix(maxtriMul);}private static void printMatrix(int[][] matrixA) {for (int i = 0; i < matrixA.length; i++) {for (int j = 0; j < matrixA.length; j++) {System.out.print(matrixA[i][j] + " ");}System.out.println();}}private static int[][] matrixMultiplication(int[][] matrixA, int[][] matrixB) {int maxtriMul[][] = new int[3][3];for (int i = 0; i < matrixB.length; i++) {for (int j = 0; j < matrixB.length; j++) {for (int k = 0; k < matrixA.length; k++) {maxtriMul[i][j] += matrixA[i][k] * matrixB[k][j];}}}return maxtriMul;}}// Time complexity : O(n^3)// Space Complexity : O(n^2)
C++
#include <bits/stdc++.h>using namespace std;//function to multiply two maytricesvoid multiplyMatrix(int arr[][3],int brr[][3],int n){//matrix which store the resultint crr[3][3];for(int i=0;i<n;i++){for(int j=0;j<n;j++){crr[i][j]=0;for(int k=0;k<n;k++){crr[i][j]+=arr[i][k]*brr[k][j];}}}//store the final result back to//arrfor(int i=0;i<n;i++){for(int j=0;j<n;j++)arr[i][j]=crr[i][j];}}int main(){//first matrix 3 X 3 matrixint arr[][3]={{6,2,3},{4,3,2},{4,5,7}};//second matrix 3 X 3int brr[][3]={{4,6,2},{2,6,1},{1,5,1}};int n=3;multiplyMatrix(arr,brr,n);cout<<"Result after multiply is\n";for(int i=0;i<n;i++){for(int j=0;j<n;j++)cout<<arr[i][j]<<" ";cout<<"\n";}return 0;}//Time Complexity: O(n^3)//Space Complexity:O(n^2)
No comments:
Post a Comment