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-+-

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is On HTML code is OffTrackbacks are On Pingbacks are On Refbacks are Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post Nervous Nick Digital Photography 1 11-04-2008 02:38 AM Holgerson C++ 3 10-26-2007 07:38 AM marzdra@yahooo.con Computer Support 1 12-16-2006 09:18 PM lvcargnini VHDL 3 07-05-2006 07:21 AM PeterTHX DVD Video 0 08-03-2003 05:46 AM