Link to home
Start Free TrialLog in
Avatar of phoffric
phoffric

asked on

valarray submatrix representation using gslice

How should a function, foo, be defined so that it will accept a valarray (that represents a MxN matrix), so that foo operates on a sub-matrix?

I've read enough to know that I need to use gslice to pick out the sub-matrix. (I don't want to use the mask or indirect because the original matrix and the sub-matrix will be huge.)

As an example of what foo will see..
Say, original valarray has a 35 elements representing a 5 row by 7 col matrix; and the sub-matrix starts in the 2nd row, 2nd column (i.e., offset 8), and whose dimensions are 3 rows by 4 cols.
foo should just print out the sub-matrix values.

Suppose the initial values of the valarray are just set to the index number (i.e., first element is 0). It looks like:
 0  1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 32 33 34

Open in new window

Then with start offset, S = 8, nRow = 3, nCol = 4, foo should be able to operate on the following sub-matrix:
 8  9 10 11
15 16 17 18
22 23 24 25

Open in new window


I started with this, but not sure how to use gslice and set up gslice params correctly.
foo should use this gslice, I think.
#include <iostream>
#include <valarray>
using namespace std;

template<class T>
void print(const valarray<T> &v) {
   for(size_t i = 0; i < v.size(); ++i) 
      cout << '\t' << v[i];
   cout << endl;
}

template<class T>
void init(valarray<T>& v)
{
   for(size_t i=0; i < v.size(); ++i)
   {
      v[i] = i;
   }
}

void foo()
{
}

int main()
{
   const int M=7, N=5;
   valarray<int> va(M*N);
   init(va);
   size_t sizes[2]   = {3, 4};
   size_t strides[2] = {7, 1};
   gslice gs;
   foo();
   print(va);
}

Open in new window

I was told not to use boost or my own class to handle the sub-matrix due to optimization plans.
Thanks.
ASKER CERTIFIED SOLUTION
Avatar of phoffric
phoffric

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of phoffric
phoffric

ASKER

I suppose that I can make a class that includes a valarray type and defines an operator () taking two arguments corresponding to row and column indices.