【问题标题】:Matlab: get rid of loopMatlab:摆脱循环
【发布时间】:2019-01-06 02:37:23
【问题描述】:

我正在处理二进制信息,从文件中读取。这是一个 40 位格式的数字序列,在我的例子中,前 8 位应该被忽略,另外 32 位是“混洗”的 32 位单精度 IEEE 754 格式。这种“洗牌”非常简单:当我采用以下位顺序时,我得到了正确的 IEEE 754 binary32:24-32、17-24、9-16

所有这些都是用下面的代码模拟的。

问题:如何改进下面的代码以使其更快,摆脱“for”循环并使用高效的 MATLAB 矩阵运算?

a = (1:5*8*1000000)'; % represent indices of bits binary information, read from file
tic
a_reshaped = reshape(a, 8, [])'; 
toc %Elapsed time is 0.176375 seconds.
n_elem = size(a_reshaped,1)/5;
result = zeros(n_elem,8*4);
for i = 1:n_elem
    result(i,:) = [a_reshaped(5*i,:) a_reshaped(5*i-1,:) a_reshaped(5*i-2,:) a_reshaped(5*i-3,:)];
end
toc %Elapsed time is 4.243868 seconds.

【问题讨论】:

  • 该文件的字节序似乎与您的计算机不同。您可以在打开文件时更改字节顺序,因此您以后不需要重新排列字节。

标签: matlab for-loop matrix


【解决方案1】:

试试这个:

ind = size(a_reshaped,1):-1:1;
ind(end:-5:1) = []; %remove the indices for rows you don't need
a_reduced = a_reshaped(ind,:);
result = flipud(reshape(a_reduced',8*4,[])');

【讨论】:

    【解决方案2】:

    “for”循环可以在以下一行代码中替换,速度更快:

    result(1:n_elem,:) = [a_reshaped(5*(1:n_elem),:) a_reshaped(5*(1:n_elem)-1,:) a_reshaped(5*(1:n_elem)-2,:) a_reshaped(5*(1:n_elem)-3,:)]; %Elapsed time is 0.766840 seconds.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多