Velocity Reviews > C++ > Can I print elements of a simple matrix with out manual nested loop?

# Can I print elements of a simple matrix with out manual nested loop?

SUPER_SOCKO
Guest
Posts: n/a

 02-28-2005
Suppose I have a matrix M x N dimension.
Normally, to print all of the elements in the matrix. I write the
following codes:

Suppose M = 5, N = 4:

for(int j=0; j<5; ++j) {
for(int k=0; k<4; ++k) {
cout << matrix[M][N] << " ";
}
cout << endl;
}

If my matrix class has method for return number of dimension and
dimension size such as:

numDimension(matrix); // return 2 becase the matrix has M x N = 2
dimensions.

sizeDimension(0); // return 5 -- size of M
sizeDimension(1); // return 4 -- size of N

How to write some code that print all element of the matrix with out
code nested loops by hand?

Thanks

Nalerk

Ben Hetland
Guest
Posts: n/a

 02-28-2005
SUPER_SOCKO wrote:

> How to write some code that print all element of the matrix with out
> code nested loops by hand?

You can just create a double loop, where the outermost loop iterates of
the number of dimensions, while the inner loop goes from 0 to
"sizeDimension(current_dim)".

However, you will need to decide yourself how to lay out a -- say --
5-dimensional matrix in the 2-dimensional "cout space".

You will also need to calculate your indices yourself somehow, but your
you? (Or how does it otherwise implement matrix[n][m] in a 2-dim.
matrix, and say matrix[n][m][p][q][r] in a 5-dimensional one?) Along the
way, you will need to maintain som state variables, to keep track of
(and temporarily remember) indices you are starting at in each
direction. Some stack- or list-like functionality probably; hint:
std::vector.

Another way to solve this latter is considering some kind of recursive
implementation.

Regards,

-+-Ben-+-