# Row-sum and column-sum of a square matrix

Page 1 of 1

## 0 Replies - 1784 Views - Last Post: 06 March 2011 - 09:03 AM

### #1 Tapas Bose

• D.I.C Regular

Reputation: 23
• Posts: 472
• Joined: 09-December 09

# Row-sum and column-sum of a square matrix

Posted 06 March 2011 - 09:03 AM

Description: The following shell script computes the row and column sum for each row and column of a matrix taking input from user
```#!/bin/bash

## Shell script that takes a n*n matrix as input. The program is required to
## find out the sum of individual row element and individual column element
##
## This script simulate a two dimensional array by a one dimensional array

echo -n "Enter the number of row or column: "

echo
declare -a array

rowSquare=`expr \$row * \$row`

for (( i = 0; i < \$row; i++ ))
do
k=0
for (( j = 0; j < \$rowSquare; j += \$row ))
do
## In the following script the indexes of a 3x3 (for row=3) matrix will be represented as
##
## 0+0+0 0+3-2 0+6-4
## 1+0+2 1+3+0 1+6-2
## 2+0+4 2+3+2 2+6+0
##
## By 0+0+0 it means (value of i)+(value of j)+(value of adjustment)

index=`expr \$i + \$j + \$adjustment`
echo -n "Enter the value of A`expr \$i + 1``expr \$k + 1`: "
k=`expr \$k + 1`
done
done

echo
echo "The given matrix is: "

for (( i = 0; i < \$row; i++ ))
do
for (( j = 0; j < \$rowSquare; j += \$row ))
do
index=`expr \$i + \$j + \$adjustment`
echo -n "\${array[index]} "
done
echo
done

for (( i = 0; i < \$row; i++ ))
do
colSum=0
rowSum=0
for (( j = 0; j < \$rowSquare; j += \$row ))
do
colIndex=`expr \$i + \$j`
colSum=`expr \$colSum + \${array[colIndex]}`
rowIndex=`expr \$i + \$j + \$adjustment`
rowSum=`expr \$rowSum + \${array[rowIndex]}`
done
echo
echo "Sum of `expr \$i + 1`th column: \$colSum"
echo "Sum of `expr \$i + 1`th row: \$rowSum"
done

echo
echo -n "Press enter to continue ..."