Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

BASH Using only pure BASH (awk, python, etc are not allowed!) write a function t

ID: 3911429 • Letter: B

Question

BASH

Using only pure BASH (awk, python, etc are not allowed!) write a function that adds two matrices with an unknown number of rows and columns and returns the sum of the two matrices as follows:

The input matrix is made of integers seperated by tabs with a new line character on the end, as seen here:

1 2 3 4

5 6 7 8

Example matrix (must taken any size matrices):

When our program runs, we will get this in stdout:

Our output matrix is seperated by tabs and new line characters as well.

$ cat ml 1 5 $cat m2 1 2 4 6 7 2 4 6 5 7

Explanation / Answer

#! /bin/bash
file1="m1.txt"
file2="m2.txt"


echo "Reading input files"
readarray -t mat1 < "$file1" || exit 1
readarray -t mat2 < "$file2" || exit 1

# Line number
n1=${#mat1[*]}
n2=${#mat2[*]}
((n = n1<n2 ? n1:n2))

for ((i=0; i<n; i++)); do
    line1=(${mat1[i]})
    line2=(${mat2[i]})

    line3=(${line1[0]})

    for ((j=1; j<=3; j++)); do
        line3+=($(echo "${line1[j]}+${line2[j]}"|bc))
    done

    echo "${line3[@]}"
done

echo "done"
exit 0