Matlab:摆脱循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Matlab:摆脱循环相关的知识,希望对你有一定的参考价值。
我正在使用二进制信息,从文件中读取。这是一个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.
答案
试试这个:
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,[])');
另一答案
“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.
以上是关于Matlab:摆脱循环的主要内容,如果未能解决你的问题,请参考以下文章