⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mwarrayio.cpp

📁 用VC读写Matlab中数据的例子
💻 CPP
字号:
// mwArrayIO.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "matlab.hpp"
#include "mex.h"
#include "matrix.h"

#include "fstream.h"

int main(int argc, char* argv[])
{
	/*采用文件流将变量输出到文件*/
	char filename[]="数据输出.txt";
	mwArray m_data;
	m_data = rand(3,3);
	ofstream out_file("数据输出.txt", ios::out);
	out_file << m_data << ends;
	m_data = magic(4);
	out_file << m_data << ends;
	out_file.close();
	/*采用文件流将存储在文件中的变量读入*/
	mwArray A,B;
	ifstream in_file("数据输出.txt", ios::in);
	in_file>>A>>B;

	cout << "采用文件流从文件"<<filename<<"中读入的变量如下:" << endl;
	cout << A << endl;
	cout << B << endl;

	/*通过MATLAB C++ 数学库自己的文件IO实现变量的读写*/
	char filename1[]="数据输出1.txt";
	mwArray mwfile(filename1);
	mwArray fd = fopen(mwfile,"w");
	fprintf(fd,"%f %f %f\n",A);
	fprintf(fd,"\n");
	fprintf(fd,"%4d %4d %4d %4d\n",B);
	fclose(fd);

	mwArray szA,szB,C,D;
	szA = horzcat(3,3);
	szB = horzcat(4,4);

	fd = fopen(mwfile,"r");
	C = fscanf(fd,"%f %f %f\n",szA);
	D = fscanf(fd,"%4d %4d %4d %4d\n",szB);

	cout << "采用文件IO从文件"<<filename1<<"中读入的变量如下:"<<endl;
	cout << C << endl;
	cout << D << endl;

	fclose(fd);

	/*字符型mwArray对象数据通过文件IO的读写*/
	char filename2[]="字符串输出.txt";
	mwArray s1("实践是检验真理的唯一标准!");
	mwArray s2("没有付出,就没有收获!");
	mwArray s3,s4;
	mwArray mwfile1(filename2);
	fd = fopen(mwfile1,"wr");
	fprintf(fd,"%s\n",s1,s2);
	fclose(fd);
	fd = fopen(mwfile1,"r");
	s3 = fgetl(fd);
	s4 = fgetl(fd);
	cout <<"从文件"<<filename2<<"中读入的字符串变量如下:"<<endl; 
	cout << s3 <<endl;
	cout << s4 <<endl;
	fclose(fd);

	/*采用MAT文件导入和导出数据*/
	char filename3[]="dataoutput.mat";
	save(filename3,"A",A,"B",B,"s1",s1,"s2",s2);
	mwArray a1,b1,c1,d1;
	load(filename3,"A",&a1,"B",&b1,"s1",&c1,"s2",&d1);
	if((tobool(A==a1))&&
	   (tobool(B==b1))&&
	   (tobool(s1==c1))&&
	   (tobool(s2==d1)))
	{
		cout <<"采用MAT文件进行数据导入和导出正确!\n" << endl;
	}
	else
	{
		cout <<"采用MAT文件进行数据导入和导出错误!\n" << endl;
	}

	/*采用将mwArray对象数据输出到字符串中*/
	mwArray mwstr;
	mwstr = sprintf("%6.4f %6.4f %6.4f;\n",A);
	cout << "将对象A的数据输出到到字符串中:" <<endl;
	cout << mwstr << endl;
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -