matlab复制矩阵到c

方法1:运行脚本,选中matlab中多行多列矩阵的数据复制,输出线性排列的数据(先行后列),按英文逗号隔开,在c文件中粘贴使用。
import os, re, sys, time, pyperclip 


def convert():
    print("Exit: ctrl+c or copy 'q'\n")
    recent = ""
    tmp = ""  
    while True:
        tmp = pyperclip.paste() 
        
        if tmp == 'q': 
            break

        try:
            if tmp != recent:  
                recent = tmp
                
                changed = re.sub(r"\s{2,}", ", ", recent)  # matlab纵向
                changed = changed.replace("\t", ", ")  #matlab横向
                pyperclip.copy(changed)  
                print("Converted:\n%s\n" % str(changed))
                
                recent = changed
            time.sleep(0.1)
        except KeyboardInterrupt: 
            break


if __name__ == "__main__":
    convert()
方法2:创建txt文件,直接复制到txt文件中(会用空格和换行符隔开),之后用c函数从中读取
typedef struct {
	double** mat;
	int row, col;
}Matrix2d;

Matrix2d initMatrix2d(int row, int col, double* X) {
	Matrix2d M;
	M.row = row;
	M.col = col;
	M.mat = (double**)malloc(sizeof(double*) * row);
	for (int i = 0; i < row; i++) {
		M.mat[i] = (double*)malloc(sizeof(double) * col);
	}

	if (X != 0) {
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				M.mat[i][j] = *(X + i * col + j);
			}
		}
	}

	return M;
}

void getdatafromtxt(Matrix2d m, char* filename) {
	int row = m.row, col = m.col;

	FILE* fpin_amp;
	fopen_s(&fpin_amp, filename, "rt");

	for (int i = 0; i < row; i++) {
		for (int j = 0; j < col; j++) {
			fscanf_s(fpin_amp, "%lf", &m.mat[i][j]);
		}
	}
}


void main() {
	Matrix2d m = initMatrix2d(3, 3, 0);
	char* filename = "data.txt";
	getdatafromtxt(m, filename);
}

其中,示例的data.txt
在这里插入图片描述

tips:对于数据量过大的矩阵,直接赋值静态初始化会导致栈溢出,推荐方法2

你可能感兴趣的:(python工具,matlab,矩阵,开发语言,c)