Results 1 to 2 of 2

Thread: vector of vector and computes

  1. #1
    Join Date
    Jan 2006
    Posts
    976
    Thanks
    53
    Qt products
    Qt3
    Platforms
    Windows

    Default vector of vector and computes

    Hello,
    I have a matrix of int (vector of vector); the problem is that I need to compute the mean of each column (the matrix can be 500 x200); so to do this I did:
    Qt Code:
    1. foreach (iter_column) {
    2. float sum = 0;
    3. iter_line.setFirstLine;
    4. foreach(iter_line) {
    5. sum += iter_line[iter_coulmn]. value;
    6. }
    7. mean = sum / nOfLine;
    8. }
    To copy to clipboard, switch view to plain text mode 
    The problem is that I have to do "two for" one inside other; I thought If is better to do something like to tie a vector<coulum> and do:
    Qt Code:
    1. class Column {
    2. public:
    3. vector<double> _value;
    4. };
    5. vector<Column> col; //to fill col properly
    6. foreach (col) {
    7. int sum = std::accumulate(col.begin(), col.end(), 0);
    8. mean = sum / col.size();
    9. }
    To copy to clipboard, switch view to plain text mode 

    Will be the second way better/faster? Any other ways to improve?
    Regards

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,359
    Thanks
    3
    Thanked 5,015 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: vector of vector and computes

    It won't be faster, because std::accumulate will iterate the vector as well... What you can do is to calculate all columns at once and store results in a temporary vector. It won't be much faster though - you have to iterate all columns in all rows ending up with a complexity of O(n x m) anyway. The only benefit you might have is proper use of cpu cache. You could try making things faster by calculating more than one cell at once (by reading/summing all columns in one machine instruction), but you can have overflows then.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.