Search code examples
c++filematrixsizesparse-matrix

c++ read matrix of unkown size


This is my problem, I need to read from a text file a certain matrix of int, without knowing the size of it

suppose for instance:

"matrix.dsv"

1,0,1,0,0,0,1,0
0,1,1,1,1,1,1,1
0,0,0,0,0,0,0,0
0,0,0,1,0,0,0,0

Is there any way of knowing the size of the matrix without importing it?

Since I will choose a different way of memorizing it (vector, sparse matrix, full matrix) depending on the sparseness, is there also a way of counting the nonzero elements?

Thank you very much (sorry for the lame question, i'm quite new to managing files!)

EDIT: Thank you coincoin! One last question, how does cin reacts to the end of the line? Or better, how do I increment one of the indexes when I finish a line? Thanks ;)


Solution

  • Unfortunately, you have to read the file in order to know the size of the matrix unless you have information in the file name or at the beginning of your file.

    The question is a little broad.
    std::vector should be the way to go since you can dynamically add elements with push_back() for sparse or dense storage. Prefer flatten linear (one dimension) storage.
    Processing the file should be one pass, you read element by element, check and add to a counter if it is zero.
    When reaching end of file and know the size of your matrix, you can rearrange the data.

    If you can you should try to use known libraries for convenient Matrix classes and methods such as Eigen, Armadillo if you are doing linear algebra.