没有什么可以被认为是等价的。 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。还存在用于此类事物的第三方库。 This answer 包含一些。
当然,您也可以自己编写。有几种方法可以做到这一点,但它可能看起来有点像这样:
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 中实现它需要什么。