首页 > 代码库 > MATLAB保存矩阵的几种方法的比较
MATLAB保存矩阵的几种方法的比较
最近项目中需要使用MATLAB优秀的矩阵计算功能,然后再把矩阵保存到文件中,供其他语言的程序使用。这就需要把矩阵保存成文件格式,而不是mat形式。这里主要使用到了三种方法: by木子肖子
1. dlmwrite: 写ASCII编码的有分隔符的矩阵。
function dlmwrite(filename, m, varargin) %DLMWRITE Write ASCII delimited file. % % DLMWRITE('FILENAME',M) writes matrix M into FILENAME using ',' as the % delimiter to separate matrix elements. % % DLMWRITE('FILENAME',M,'DLM') writes matrix M into FILENAME using the % character DLM as the delimiter. % % DLMWRITE('FILENAME',M,'DLM',R,C) writes matrix M starting at % offset row R, and offset column C in the file. R and C are zero-based, % so that R=C=0 specifies the first value in the file. % % DLMWRITE('FILENAME',M,'ATTRIBUTE1','VALUE1','ATTRIBUTE2','VALUE2'...) % An alternative calling syntax that uses attribute value pairs for % specifying optional arguments to DLMWRITE. The order of the % attribute-value pairs does not matter, as long as an appropriate value % follows each attribute tag. % % DLMWRITE('FILENAME',M,'-append') appends the matrix to the file. % without the flag, DLMWRITE overwrites any existing file. % % DLMWRITE('FILENAME',M,'-append','ATTRIBUTE1','VALUE1',...) % Is the same as the previous syntax, but accepts attribute value pairs, % as well as the '-append' flag. The flag can be placed in the argument % list anywhere between attribute value pairs, but not between an % attribute and its value. % % USER CONFIGURABLE OPTIONS % % ATTRIBUTE : a quoted string defining an Attribute tag. The following % attribute tags are valid - % 'delimiter' => Delimiter string to be used in separating matrix % elements. % 'newline' => 'pc' Use CR/LF as line terminator % 'unix' Use LF as line terminator % 'roffset' => Zero-based offset, in rows, from the top of the % destination file to where the data it to be % written. % 'coffset' => Zero-based offset, in columns, from the left side % of the destination file to where the data is to be % written. % 'precision' => Numeric precision to use in writing data to the % file, as significant digits or a C-style format % string, starting with '%', such as '%10.5f'. Note % that this uses the operating system standard % library to truncate the number. % % % EXAMPLES: % % DLMWRITE('abc.dat',M,'delimiter',';','roffset',5,'coffset',6,... % 'precision',4) writes matrix M to row offset 5, column offset 6, in % file abc.dat using ; as the delimiter between matrix elements. The % numeric precision is of the data is set to 4 significant decimal % digits. % % DLMWRITE('example.dat',M,'-append') appends matrix M to the end of % the file example.dat. By default append mode is off, i.e. DLMWRITE % overwrites the existing file. % % DLMWRITE('data.dat',M,'delimiter','\t','precision',6) writes M to file % 'data.dat' with elements delimited by the tab character, using a precision % of 6 significant digits. % % DLMWRITE('file.txt',M,'delimiter','\t','precision','%.6f') writes M % to file file.txt with elements delimited by the tab character, using a % precision of 6 decimal places. % % DLMWRITE('example2.dat',M,'newline','pc') writes M to file % example2.dat, using the conventional line terminator for the PC % platform. % % See also DLMREAD, CSVWRITE, NUM2STR, SPRINTF. % Brian M. Bourgault 10/22/93 % Modified: JP Barnard, 26 September 2002. % Michael Theriault, 6 November 2003 % Copyright 1984-2011 The MathWorks, Inc. %-------------------------------------------------------------------------------给定矩阵M,以读者指定的分隔符将矩阵写入文件中,可以按照C语言的形式控制写入数字的形式,如’%u‘表示整形,’%5.6f‘表示5位整数6位小数的浮点型。
此方法按矩阵的行对数字进行格式调整,并一行一行的写入文件中,效率较慢,我测试了行10^7,列2的矩阵,用了880s。
2.num2str,然后再fprintf,先将矩阵转化为字符串,然后在fprinf写入矩阵。
%NUM2STR Convert numbers to a string. % T = NUM2STR(X) converts the matrix X into a string representation T % with about 4 digits and an exponent if required. This is useful for % labeling plots with the TITLE, XLABEL, YLABEL, and TEXT commands. % % T = NUM2STR(X,N) converts the matrix X into a string representation % with a maximum N digits of precision. The default number of digits is % based on the magnitude of the elements of X. % % T = NUM2STR(X,FORMAT) uses the format string FORMAT (see SPRINTF for % details). % % Example 1: % num2str(randn(2,2),3) produces a string matrix such as % % 1.44 -0.755 % 0.325 1.37 % % Example 2: % num2str(rand(2,3) * 9999, '%10.5e\n') produces a string matrix % such as % % 8.14642e+03 % 1.26974e+03 % 6.32296e+03 % 9.05701e+03 % 9.13285e+03 % 9.75307e+02 % % See also INT2STR, SPRINTF, FPRINTF, MAT2STR. % Copyright 1984-2012 The MathWorks, Inc. %------------------------------------------------------------------------------
num2str将矩阵转化为字符串,效率和int2str差不多,比mat2str快很多。num2str也可以按照C语言的形式控制数字转化为字符串的形式。转化时是以列为单位进行的。效率挺快,转化行10^7,列2的矩阵不到1s.生成的内存大约是原矩阵的2倍左右,但中间过程占用内存较大,对于较大的矩阵可以考虑分块转化。然后就是是将字符用fprintf写入文件了。
3.fprintf函数
%FPRINTF Write formatted data to text file. % FPRINTF(FID, FORMAT, A, ...) applies the FORMAT to all elements of % array A and any additional array arguments in column order, and writes % the data to a text file. FID is an integer file identifier. Obtain % FID from FOPEN, or set it to 1 (for standard output, the screen) or 2 % (standard error). FPRINTF uses the encoding scheme specified in the % call to FOPEN. % % FPRINTF(FORMAT, A, ...) formats data and displays the results on the % screen. % % COUNT = FPRINTF(...) returns the number of bytes that FPRINTF writes. % % FORMAT is a string that describes the format of the output fields, and % can include combinations of the following: % % * Conversion specifications, which include a % character, a % conversion character (such as d, i, o, u, x, f, e, g, c, or s), % and optional flags, width, and precision fields. For more % details, type "doc fprintf" at the command prompt. % % * Literal text to print. % % * Escape characters, including: % \b Backspace '' Single quotation mark % \f Form feed %% Percent character % \n New line \\ Backslash % \r Carriage return \xN Hexadecimal number N % \t Horizontal tab \N Octal number N % For most cases, \n is sufficient for a single line break. % However, if you are creating a file for use with Microsoft % Notepad, specify a combination of \r\n to move to a new line. % % Notes: % % If you apply an integer or string conversion to a numeric value that % contains a fraction, MATLAB overrides the specified conversion, and % uses %e. % % Numeric conversions print only the real component of complex numbers. % % Example: Create a text file called exp.txt containing a short table of % the exponential function. % % x = 0:.1:1; % y = [x; exp(x)]; % fid = fopen('exp.txt','w'); % fprintf(fid,'%6.2f %12.8f\n',y); % fclose(fid); % % Examine the contents of exp.txt: % % type exp.txt % % MATLAB returns: % 0.00 1.00000000 % 0.10 1.10517092 % ... % 1.00 2.71828183 % % See also FOPEN, FCLOSE, FSCANF, FREAD, FWRITE, SPRINTF, DISP. % Copyright 1984-2009 The MathWorks, Inc. % Built-in function.
此函数以列为顺序将矩阵按照指定的格式转化后写入到文件,优点是占用内存小,(边转化边写入),效率高,(和第二种方法时间上差不多),推荐这种方法。
MATLAB保存矩阵的几种方法的比较
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。