ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – Matlab中的高效字符串连接

2019-06-24 17:55:35  阅读:340  来源: 互联网

标签:python string-concatenation matlab string


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

Python字符串连接方法

方法1:天真追加

def method1():
    out_str = ''
    for num in xrange(loop_count):
        out_str += `num`
    return out_str

方法4:构建字符串列表,然后加入它

def method4():
  str_list = []
  for num in xrange(loop_count):
    str_list.append(`num`)
  return ''.join(str_list)

方法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字符串连接方法

方法1:天真追加

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.

解决方法:

由于Matlab更喜欢在数组上执行向量化操作,并且在使用for循环时效率很低,因此性能最佳的通用解决方案是创建包含所有字符串的单元格数组,并使用[str_array {:}]或使用strjoin sprintf连接它们(见下文)取决于您的需求.

对于某些操作,例如从数组中创建逗号分隔的字符串,可以使用更有效的解决方案,例如

numeric_array = rand(1 ,100000);
out_str = sprintf('%d,', numeric_array);
out_str = out_str(1:end-1);

因为它一次执行字符串转换和串联.

作为旁注,out_str = sprintf(‘%s’,str_array {:}); out_str = out_str(1:end-1)比使用Matlab 2013a的计算机上strjoin(str_array {:})快约10倍.

标签:python,string-concatenation,matlab,string
来源: https://codeday.me/bug/20190624/1280774.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有