首页 > 解决方案 > 什么是 C 等价于 Matlab 的索引表达式 A(:,n)?

问题描述

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

标签: cmatlab

解决方案


没有什么可以被认为是等价的。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];
}

对不起,但它不会比纯 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];
}
    

请不要将此视为可以复制粘贴的内容。这只是为了说明在 C 中实现这一点需要什么。


推荐阅读