Advertisement
Shailrshah

Matrix Addition, Subtraction and Multiplication

Aug 30th, 2014
435
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.35 KB | None | 0 0
  1. #!/bin/bash
  2. function inputMatrix(){
  3.     echo "For Matrix A:-"
  4.     for (( i=0; i<rowA; i++ ))
  5.     do
  6.         for (( j=0; j<columnA; j++ ))
  7.         do
  8.             echo "Value at [$i][$j] : "
  9.             read MatrixA[$i$j]
  10.         done
  11.     done
  12.     echo "For Matrix B:-"
  13.     for (( i=0; i<rowB; i++ ))
  14.     do
  15.         for (( j=0; j<columnB; j++ ))
  16.         do
  17.             echo "Value at [$i][$j] : "
  18.             read MatrixB[$i$j]
  19.         done
  20.     done
  21. }
  22. function add(){
  23.     for (( i=0; i<rowA; i++ ))
  24.     do
  25.         for (( j=0; j<columnA; j++ ))
  26.         do
  27.             let MatrixC[$i$j]=${MatrixA[$i$j]}+${MatrixB[$i$j]}
  28.         done
  29.     done
  30. }
  31. function sub(){
  32.     for (( i=0; i<rowA; i++ ))
  33.     do
  34.         for (( j=0; j<columnA; j++ ))
  35.         do
  36.             let MatrixC[$i$j]=${MatrixA[$i$j]}-${MatrixB[$i$j]}
  37.         done
  38.     done
  39. }
  40. function mul(){
  41.     for (( i=0; i<rowA; i++ ))
  42.     do
  43.         for (( j=0; j<columnB; j++ ))
  44.         do
  45.             sum=0
  46.             for (( k=0; k<columnA; k++ ))
  47.             do
  48.                 sum=`expr "$sum+(${MatrixA[$i$k]} * ${MatrixB[$k$j]})"|bc`
  49.             done
  50.             MatrixC[$i$j]=$sum
  51.         done
  52.     done
  53. }
  54. function displayMatrix(){
  55.     for (( i=0; i<rowA; i++ ))
  56.     do
  57.         for (( j=0; j<columnB; j++ ))
  58.         do
  59.             echo -n ${MatrixC[$i$j]}" "
  60.         done
  61.         echo ""
  62.     done
  63. }
  64. rowA=2
  65. columnA=2
  66. rowB=2
  67. columnB=2
  68. inputMatrix
  69. echo -n "1.Add 2. Subtract 3. Multiply: "
  70. read ip
  71. case $ip in
  72.     1):
  73.         add;;
  74.     2):
  75.         sub;;
  76.     3):
  77.         mul;;
  78. esac
  79. displayMatrix
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement