前段时间我偶然发现了document。它评估了python中几种连接方法的性能。以下是它比较的6种方法中的4种:
def method1():
out_str = ''
for num in xrange(loop_count):
out_str += `num`
return out_str
def method4():
str_list = []
for num in xrange(loop_count):
str_list.append(`num`)
return ''.join(str_list)
def method5():
from cStringIO import StringIO
file_str = StringIO()
for num in xrange(loop_count):
file_str.write(`num`)
return file_str.getvalue()
def method6():
return ''.join([`num` for num in xrange(loop_count)])
结果的结论如下:
我会在大多数真实程序中使用方法6。这很快,而且很容易理解。它确实需要您能够编写一个表达式,该表达式返回要追加的每个值。有时这样做不方便 - 例如,当有几个不同的代码块生成输出时。在这些情况下,您可以在方法4和方法5之间进行选择。
阅读本文后,我意识到我不知道方法5和6.在大多数情况下,我现在更喜欢使用方法5,因为它允许我以与我想要的方式相同的方式写入字符串。文件。
我的问题如下,matlab中用于字符串连接的不同技术是什么?我几乎没有在matlab中处理字符串,但是我想出了一个需要我写一个字符串的问题。我想到的一个解决方案是写入临时文件并在完成后读取文件。但在此之前,我决定询问是否有更好的选择。现在这里是matlab中一个天真的附加方法:
function out_str = method1(loop_count)
out_str = '';
for num=1:loop_count
out_str = [out_str num2str(num)]; %#ok<AGROW>
end
end
Matlab与方法4,5和6中是否有类似的方法可用于效率比较?
修改
这里有一些方法类似于python中的方法5(写入文件):
function out_str = method2(loop_count)
fid = fopen('._tmpfile.tmp', 'w');
for num=1:loop_count
fprintf(fid, '%d', num);
end
fclose(fid);
out_str = fileread('._tmpfile.tmp');
end
这是一个简单的测试:
>> tic; tmp1 = method1(100000); toc
Elapsed time is 13.144053 seconds.
>> tic; tmp2 = method2(100000); toc
Elapsed time is 2.358082 seconds.
答案 0 :(得分:2)
由于Matlab更喜欢对数组执行向量化操作,并且在使用for循环时效率很低,因此性能最佳的通用解决方案是创建包含所有字符串的单元格数组,并使用{{ 1}}或使用 [str_array{:}]
strjoin
加入(见下文),具体取决于您的需求。
对于某些操作,例如从数组中创建逗号分隔的字符串,可以使用更有效的解决方案,例如
sprintf
因为它同时执行字符串转换和连接。
旁注numeric_array = rand(1 ,100000);
out_str = sprintf('%d,', numeric_array);
out_str = out_str(1:end-1);
比使用Matlab 2013a的计算机上的out_str = sprintf('%s ', str_array{:});out_str = out_str(1:end-1)
快十倍。
答案 1 :(得分:2)
一般来说,有一种快速的方法可以增长经常没有提到的矢量连接。这是一个明显的例子(连接数字,但在matlab中字符也被视为数字):
%What you will typically find in sample code
loop_count=1e4
out_str = [];
tic
for num=1:loop_count
out_str = [out_str num]; %#ok<AGROW>
end
toc
% What typically runs faster
out_str = [];
tic
for num=1:loop_count
out_str(end+1) = num;
end
toc
会给出
Elapsed time is 0.077540 seconds.
Elapsed time is 0.004776 seconds.
当然,如果您在开始之前已经知道要连接的所有内容,游戏就会发生变化。假设您想要在向量中连接数字的字符串表示:
%Vectorized code typically runs fastest
v =1:loop_count
M=[num2str(v)];
tic
M=M(~M==' ');
toc
会给出
Elapsed time is 0.001903 seconds.