matlab 串,Matlab中的高效串接

不久前我偶然发现了这个document。它评估了python中几种连接方法的性能。以下是它比较的6种方法中的4种:

Python字符串连接方法

方法一:天真附加def method1():

out_str = ''

for num in xrange(loop_count):

out_str += `num`

return out_str

方法4:建立一个字符串列表,然后将其连接到

^{pr2}$

方法5:写入伪文件def method5():

from cStringIO import StringIO

file_str = StringIO()

for num in xrange(loop_count):

file_str.write(`num`)

return file_str.getvalue()

方法6:列出理解def method6():

return ''.join([`num` for num in xrange(loop_count)])

结果得出如下结论:I would use Method 6 in most real programs. It's fast and it's easy to understand. It does require that you be able to write a single expression that returns each of the values to append. Sometimes that's just not convenient to do - for example when there are several different chunks of code that are generating output. In those cases you can pick between Method 4 and Method 5.

读完这篇文章后,我意识到我不知道方法5和方法6。在大多数情况下,我现在更喜欢使用方法5,因为它允许我以与写入文件相同的方式写入字符串。在

我的问题是,在matlab中,字符串连接有哪些不同的技术?我在matlab中很少处理字符串,但是我遇到了一个需要我编写字符串的问题。我想到的一个解决方案是写入一个临时文件,并在完成后读取该文件。但在做这件事之前,我决定问问是否有更好的选择。下面是matlab中一个简单的附加方法:

Matlab字符串连接方法

方法一:天真附加function out_str = method1(loop_count)

out_str = '';

for num=1:loop_count

out_str = [out_str num2str(num)]; %#ok

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值