Matlab:摆脱循环

问题描述 投票:0回答:2

我正在使用二进制信息,从文件中读取。这是一个40位格式的数字序列,在我的情况下应该忽略前8位,另外32位是“混洗”32位单精度IEEE 754格式。这个“shuffle”非常简单:当我按照以下顺序排列时,我得到了正确的IEEE 754二进制32: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
2个回答
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,[])');

0
投票

“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.
© www.soinside.com 2019 - 2024. All rights reserved.