c - 什么是 C 等价于 Matlab 的索引表达式 A(:,n)?
问题描述
在 Matlab 中,A(:,n)
是矩阵 A 的第 n 列。C 中的等效实现是什么?
解决方案
没有什么可以被认为是等价的。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 中实现这一点需要什么。
推荐阅读
- c# - 如何在 Mocked IQueryable 对象上实现 Count 方法
- php - php中的curl超时与curl soap xml调用
- java - 在数组列表中使用来自控制器的值实现 ComboBox
- udp - 不同机器上的 UDP 套接字服务器/客户端不会通信
- powerbi - 如何使用 dax 根据值计算非空白行数
- java - 不兼容的类型:int 不能转换为整数
- java - 如何只打印数组的最后一个元素?
- character-encoding - SikuliX IDE 使用虚线字符
- javascript - 从数组中获取前 6 个元素
- python - 在 jupyter notebook 中一个接一个地运行两个 file.py