COSC 420 – High-Performance Computing Lab 2

$30.00

Category: You will Instantly receive a download link for .zip solution file upon Payment || To Order Original Work Click Custom Order?

Description

5/5 - (3 votes)

1 Preliminaries
Recall that in the mathematical definition of a matrix, we say that A is a real n × m matrix if
A =


a1,1 a1,2 a1,3 . . . a1,m
a2,1 a2,2 a2,3 . . . a2,m
.
.
.
.
.
.
.
.
.
an,1 an,2 an,3 . . . an,m


where each ai,j ∈ R for i = 1, 2, 3, . . . , n and j = 1, 2, 3, . . . , m. In this notation, the matrix has n rows and
m columns.
If A and B are both of dimension n × m, then the sum is the n × m matrix C with entries given by
Ci,j = ai,j + bi,j
for i = 1, 2, . . . , n and j = 1, 2, . . . , m.
If A is an n × m matrix and B is an m × k matrix, then the product AB is matrix C, where
Ci,j =
Xm
l=1
ai,lbl,j
for i = 1, 2, . . . , n, and j = 1, 2, . . . , k; so C is a new n × k matrix. Thus the (i, j) entry of C is, in another
manner of speaking, the ith row of A, dot product with the jth column of B.
The transpose of n × m matrix A is a m × n matrix denoted as AT and defined such that (AT
)ij = Aji.
Your task below is to design and implement a data structure in C to model a matrix of real numbers,
then to define the operations of 1) addition, 2) subtraction, and 3) multiplication, and 4) transpose.
To program with matrices in C: Recall that in c++, one may declare multi-dimensional arrays. For
example: int arr[3][5] declares an array of three five-element integer arrays, containing fifteen total
integers. One way to visualize this is as follows:
[
[1, 2, 3, 4, 5], // arr[0]
[6, 7, 8, 9, 10], // arr[1]
[11,12,13,14,15] // arr[2]
]
To access the second element in the third array, one would use the syntax arr[2][1].
However, in the C language, it becomes cumbersome and less efficient to use the two-dimensional style,
due to the lack of constructors, destructors, etc. Instead, a more conventional technique is to allocate a
1
single-dimension array large enough to hold all n · m elements. Then, to access the (i, j)th element, one
needs to work a bit harder; the code really needs then to access element i· n + j. To make this a bit simpler,
a recommended helper is to use a macro (instead of a function, for efficiency).
// set up a C macro to calculate the location of element (i,j)
#define INDEX(n,m,i,j) m*i + j
// .. some code to set up sizes n and m
int* A = malloc(n*m*sizeof(int));
// populate the arrayx with random numbers, using matrix-style indexing
for(int i=0; i