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

S

SUPER_SOCKO

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
 
B

Ben Hetland

SUPER_SOCKO said:
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
already probably have your "matrix" class to help you out here, don't
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-+-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top