与 Matlab 的索引表达式 A(:,n) 等效的 C 是什么?

1 c matlab

在 Matlab 中,A(:,n)是矩阵 A 的第 n 列。C 中的等效实现是什么?

klu*_*utt 5

没有什么可以被认为是等效的。C 根本就不能那样工作。它没有内置对更高级别数据结构的支持,并且 - 与 C++ 不同 - 您不能重载运算符。

首先,在 Matlab 中,您有一种明显的表示矩阵的方式。在 C 中你没有。这是两种方式:

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

它们都不是数学矩阵。它们只是数组。此外,无论是在语言本身还是标准库中,都没有内置支持将它们视为数学向量甚至列表。

然后根据你想做什么,你可以写这样的东西:

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];
}
Run Code Online (Sandbox Code Playgroud)

抱歉,但它不会比纯 C 更容易。如果您想要一种对适合高性能计算的矩阵的本机支持的低级语言,您可能想看看 Fortran。还存在用于此类事情的第三方库。这个答案包含一些。

当然你也可以自己写。有几种方法可以做到这一点,但它看起来有点像这样:

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];
}
    
Run Code Online (Sandbox Code Playgroud)

请不要把它当作可以复制粘贴的东西。只是想知道在 C 中实现它需要什么。