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.

此函数以列为顺序将矩阵按照指定的格式转化后写入到文件,优点是占用内存小,(边转化边写入),效率高,(和第二种方法时间上差不多),推荐这种方法。

时间: 2024-08-09 23:48:01

MATLAB保存矩阵的几种方法的比较的相关文章

【数值分析】误差的分析与减少及Matlab解线性方程的四种方法

1.误差的来源 模型误差:数学模型与实际问题之间的误差 观测误差:测量数据与实际数据的误差 方法误差:数学模型的精确解与数值方法得到的数值解之间的误差:例如 舍入误差:对数据进行四舍五入后产生的误差 2.减少误差的几种方法 现在,我们一般用计算机解决计算问题,使用最多的是Matlab软件.对实际问题进行数学建模时,可能存在模型误差,对数学模型进行数值求解时,我们使用的方法可能产生方法误差,我们输入计算机的数据一般是有测量误差的,计算机在运算过程的每一步又会产生舍入误差(十进制转化为二进制时可能产

JS本地保存数据的几种方法

1.Cookie 这个恐怕是最常见也是用得最多的技术了,也是比较古老的技术了.COOKIE优点很多,使用起来很方便 但它的缺点也很多: 比如跨域访问问题:无法保存太大的数据(最大仅为4KB):本地保存的数据会发送给服务器,浪费带宽 等等: 2.使用sessionStorage.localStorage localStorage: 是一种你不主动清除它,它会一直将存储数据存储在客户端的存储方式,即使你关闭了客户端(浏览器),属于本地持久层储存 sessionStorage: 用于本地存储一个会话(

浏览器保存数据的几种方法

Web产品中很多时候需要在客户端,即浏览器中保存一些必要的数据.而面临这类需求时,你应当知悉对应的解决方案不仅仅只有一种. Cookie 这是最早被使用,且至今仍被广泛采用的最简单的浏览器中保存数据方法. Cookie使用键/值形式存储数据,且数据类型只能为字符串. Cookie相关的CRUD操作: 创建 document.cookie="username=Ken"; 修改 document.cookie="username=Foo"; 和创建Cookie的语法一致

MATLAB中多行注释的三种方法

转自:http://blog.163.com/tao_love2009/blog/static/162976767201122003233343/?suggestedreading A. %{ 若干语句 %} B. 多行注释: 选中要注释的若干语句, 编辑器菜单Text->Comment, 或者快捷键Ctrl+R 取消注释: 选中要取消注释的语句, 编辑器菜单Text->Uncomment, 或者快捷键Ctrl+T C. if LOGICAL(0) 若干语句 end 这个方法实际上是通过逻辑判

TF:Tensorflor之session会话的使用,定义两个矩阵,两种方法输出2个矩阵相乘的结果—Jason niu

import tensorflow as tf matrix1 = tf.constant([[3, 20]]) matrix2 = tf.constant([[6], [100]]) product = tf.matmul(matrix1, matrix2) # method 1,常规方法 sess = tf.Session() result = sess.run(product) print(result) sess.close() # # method 2,with方法 # with tf

python 爬虫保存文件的几种方法

import os os.makedirs('./img/', exist_ok=True) IMAGE_URL = "https://morvanzhou.github.io/static/img/description/learning_step_flowchart.png" def urllib_download(): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, './img/image1.png')

Matlab中图片保存的5种方法

matlab的绘图和可视化能力是不用多说的,可以说在业内是家喻户晓的. Matlab提供了丰富的绘图函数,比如ez**系类的简易绘图函数,surf.mesh系类的数值绘图函数等几十个.另外其他专业工具箱也提供了专业绘图函数,这些值得大家深入学习好久. 今天我只是讨论下如何保存这些由Matlab绘制出来的图像呢?当然借助第三方截图软件,就算了! 1.使用imwrite 函数 如图像是img,则可以使用 imwrite(img,'result.jpg'); 这种方法保存图像大小和显示的大小事一样的.

相机标定 matlab opencv ROS三种方法标定步骤(1)

一 .理解摄像机模型,网上有很多讲解的十分详细,在这里我只是记录我的整合出来的资料和我的部分理解 计算机视觉领域中常见的三个坐标系:图像坐标系,相机坐标系,世界坐标系,实际上就是要用矩阵来表示各个坐标系下的转换 首先在图像坐标系下与相机坐标系的关系 可得出   Xcam=x/dx+x0,    Ycam=y/dy+y0  表示为矩阵形式 Xcam           1/dx   0      x0          x Ycam      =    0     1/dy   y0    *  

matlab读取cvs文件的几种方法

matlab读取CVS文件的几种方法: 1,实用csvread()函数 csvread()函数有三种使用方法: 1.M = csvread('filename')2.M = csvread('filename', row, col)3.M = csvread('filename', row, col, range) 第一种方法中,直接输入文件名,将数据读到矩阵M中.这里要求csv文件中只能包含数字. 第二种方法中,除了文件名,还指定了开始读取位置的行号(row)和列号(col).这里,行号.列号