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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值