Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass 1 column of a 2D matrix to a function in C/C++

I have a 2D C-style array from which I have to pass just one column of it to a function. How do I do that?

Basically I need the C/C++ equivalent of the MATLAB command A[:,j] which would give me a column vector. Is it possible in C/C++?

like image 432
Vivek V K Avatar asked Jul 10 '14 05:07

Vivek V K


People also ask

How do you pass a column of a 2D array to a function?

We can pass the 2D array as an argument to the function in C in two ways; by passing the entire array as an argument, or passing the array as a dynamic pointer to the function.

How can you pass one-dimensional array to a function explain with example?

Example 2: Pass Arrays to Functions To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.


2 Answers

You have 3 options,

1) Pass a pointer to your object (after moving it to the first element of the destination column)

twoDArray[0][column]

Now you can calculate the next item for this column (by jumping through the elements)

2) Create a wrapper class that would do this for you.

custom2DArray->getCol(1);
.
.
.
class YourWrapper{
 private:
   auto array = new int[10][10];
 public:
   vector<int> getCol(int col);
}

YourWrapper:: vector<int> getCol(int col){
  //iterate your 2d array(like in option 1) and insert values 
  //in the vector and return
}

3) Use a 1d array instead. You can get this info easily. By jumping through rows and accessing the value for the desired column.(Mentioning just for the sake of mentioning, don't hold it against me)

like image 54
Syed Mauze Rehan Avatar answered Oct 20 '22 23:10

Syed Mauze Rehan


int colsum(int *a, int rows, int col)
{
    int i;
    int sum = 0;
    for (i = 0; i < rows; i++)
    {
        sum += *(a + i*rows+col);
    }
    return sum;
}    


int _tmain(int argc, _TCHAR* argv[])
{
    int rows = 2;
    int cols = 2;    

    int i, j;    

    int *a;
    a = (int*)malloc(rows*cols*sizeof(int));

    // This just fills each element of the array with it's column number.
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            *(a+i*rows + j) = j;    

        }
    }

    // Returns the sum of all elements in column 1 (second from left)
    int q = colsum(a, rows, 1);

    printf("%i\n", q);
    return 0;
}

It's not exactly passing the column, it's passing a pointer to the beginning of the array and then giving it instructions on how many rows the array has and which column to concern itself with.

like image 44
BeaumontTaz Avatar answered Oct 20 '22 22:10

BeaumontTaz