1

In Matlab, A(:,n) is the nth column of Matrix A. What's the equivalent implementation in C?

klutt
  • 30,332
  • 17
  • 55
  • 95

1 Answers1

5

There is nothing that could be considered equivalent. C simply does not work that way. It does not have built in support for higher level data structures, and - unlike C++ - you cannot overload operators.

First, in Matlab you have one obvious way of representing matrices. In C you don't. Two ways are these:

  • double matrix[rows*cols]
  • double matrix[rows][cols]

And neither of them are mathematical matrices. They are simply just arrays. Furthermore, there are no built in support for treating them as mathematical vectors or even lists, neither in the language itself or the standard library.

Then depending on what you want to do, you could write something like this:

double *getCol(const double *matrix, 
               size_t col, 
               size_t row_size, 
               size_t col_size)
{
    double *column = malloc(col_size * sizeof *column);
    if(!column) exit(EXIT_FAILURE);
    for(size_t i=0; i<col_size; i++) 
        column[i] = matrix[i*row_size + col];
    return column;
}

void setCol(const double *matrix, 
            const double *col, 
            size_t row_size, 
            size_t col_size)
{
    for(size_t i=0; i<col_size; i++) matrix[i*row_size + col] = col[i];
}

Sorry, but it will not get much easier than that in pure C. If you want a lowlevel language with native support for matrices that is suitable for high performance computing you might want to have a look at Fortran instead. There also exists third party libraries for these kind of things. This answer contains a few.

You could also write your own of course. There are several ways to do that, but it could look a bit like this:

struct matrix {
    double *data;
    size_t rows;
    size_t cols;
};

double getElement(const struct matrix *mat, size_t row, size_t col)
{
    return (mat->data)[col * mat->rows + col];
}

void getCol(const struct matrix *mat, size_t col, struct matrix *output)
{
    free(output->data);
    const size_t rows = mat->rows;
    output->rows = rows;
    output->cols = 1;
    output->data = malloc(rows * sizeof *(output->data));
    if(!output->data) exit(EXIT_FAILURE);
    for(size_t i=0; i<rows; i++)
        (output->data)[i] = (mat->data)[i*rows + col];
}
    

Please do not take this as something you can copy paste. It's just to give an idea of what it would take to implement this in C.

klutt
  • 30,332
  • 17
  • 55
  • 95