arrays - 更快的整数 num2str?

标签 arrays string performance matlab numbers

我有一个名为 skj 的数组。 skj 包含 200 万行数字 (2000000x1 uint32)。

我想计算以下内容

string_skj = num2str(skj);

当我运行上面的代码行时大约需要 1 分钟,有没有更快的方法?

最佳答案

Hennadii Madan的回答让我思考是否有一种方法可以比标准 Matlab num2str(或 int2str)更有效地对列向量执行此操作,我想出了 2解决方案。

编辑:在所有这些工作之后@ Luis Mendo进来把它从水里吹出来:'(

编辑:现在@ Daniel再次改进了所有以前的选项!


给定我们的行向量,V,作为

V = uint32(randi(100, 200000, 1));

我们可以达到同样的效果

A = num2str(V);

带*

B = char(strsplit(num2str(V.')).');

或者没有num2str的错误检查

C = char(strsplit(sprintf('%d\n', V)).');
C = C(1:end-1, :); % Remove extraneous '\n'

BCA 略有不同。 num2str前加空格,' 'BC后加空格。

在下面的 DE 中预先填充了 0,因此不匹配 ABC


基准

-----num2str() on row vector [Original]-----
Elapsed time is 3.501976 seconds.
  Name           Size              Bytes  Class    Attributes

  A         200000x3             1200000  char               

-----num2str() on column vector [IKavanagh modified from Hennadii Madan]-----
Elapsed time is 0.660878 seconds.
  Name           Size              Bytes  Class    Attributes

  B         200000x3             1200000  char               

-----sprintf() on row vector [IKavanagh]-----
Elapsed time is 0.582472 seconds.
  Name           Size              Bytes  Class    Attributes

  C         200000x3             1200000  char               

-----dec2base() on row vector [Luis Mendo]-----
Elapsed time is 0.042563 seconds.
  Name           Size              Bytes  Class    Attributes

  D         200000x3             1200000  char



-----myfastint2str() on row vector [Daniel]-----
Elapsed time is 0.011894 seconds.
  Name           Size              Bytes  Class    Attributes

  E         200000x3             1200000  char 

代码

clear all
close all
clc

V = uint32(randi(100, 200000, 1));

for k = 1:50000
    tic(); elapsed = toc(); % Warm up tic/toc
end

disp('-----num2str() on row vector [Original]-----');
tic;
A = num2str(V);
toc, whos A

disp('-----num2str() on column vector [IKavanagh modified from Hennadii Madan]-----');
tic;
B = char(strsplit(num2str(V.')).');
toc, whos B

disp('-----sprintf() on row vector [IKavanagh]-----');
tic;
C = char(strsplit(sprintf('%d\n', V)).');
C = C(1:end-1, :); % Remove extraneous '\n'
toc, whos C

disp('-----dec2base() on row vector [Luis Mendo]-----');
tic;
D = dec2base(V, 10);
toc, whos D

disp('-----myfastint2str() on row vector [Daniel]-----');
tic;
E = myfastint2str(V);
toc, whos E

关于arrays - 更快的整数 num2str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555066/

相关文章:

c# - 从字符串中删除文本,直到到达某个字符

performance - 为什么要从 Node.JS 的 sqlite block 中获取数据?

java - 在 Java Swing GUI 中显示和操作 ArrayList

c - 我的 for 循环有什么问题?

javascript - 接收 var 声明字符串,只保存值

安卓。如何为具有大量资源的项目提高 Eclipse 性能?

CSS Sprite 和 HTTP 请求

arrays - 在perl中如何运作 "$_ & 1"

c++ - std::length_error 尝试从类数组输出字符串时

c++ - 从字符串中提取单个单词 C++