4. Consider a 2-d Matrix (square) of size N x N a column Write an iterative (loo
ID: 3589001 • Letter: 4
Question
4. Consider a 2-d Matrix (square) of size N x N a column Write an iterative (loop) code segment (algorithm) to compute the sum of the values in each column (one sum per column). Assuming the work unit of interest is the addition used in the summations, analyze your algorithm in terms of work and the size of the matrix (N) a. b. Now consider a 3-d Matrix (cube) of size Nx Nx N a column Write an iterative code segment (algorithm) to compute the sum of the values in each column (one sum per column). c. d. Assuming the work unit of interest is the addition used in the summations, analyze your algorithm in terms of work and the size of the matrix (N).Explanation / Answer
As any language is not specified, I am writing pseudocode for these questions.
a)
for ( col=0; col< N; col++)//select each column one by one
{
colSum = 0;
for(row=0; row< N; row++)// select each row one by one
{
colSum += Matrix[row][col];
}
print colSum;//it will print sum of each column
}
b)
Since there are N rows and N columns, to find sum of a column, we need to add the corresponding element of each row. Therefork, the total work(number of additions) it has to do is:
NxN or N2.
c)
for(2dMat=0; 2dMat< N;2dMat++)//select 2D matrices one by one
{
for ( col=0; col< N; col++)//select each column one by one
{
colSum = 0;
for(row=0; row< N; row++)// select each row one by one
{
colSum += Matrix[2dMat][row][col];
}
print colSum;//it will print sum of each column
}
}
d)
Here, we are selecting 2d matrices(which are total N) one by one, and rest is same as b).
and so total work is (NxNxN) or N3.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.