向量化Matlab/八度FOR循环 [英] vectorizing a matlab / octave FOR loop
问题描述
对于如何将其向量化为for循环,我有些困惑,请参见下面的代码:
I'm a little confused as to how to vectorize this for loop see code below:
array1=[xfreq_orig,yamp_orig,yamp_inv,phase_orig] %frequency, amplitudes, phases to use
t_rebuilt=linspace(0,2*pi,44100)
aa_sig_rebuilt_L=zeros(1,length(t_rebuilt));
aa_sig_combined_L=zeros(1,length(t_rebuilt));
sig_full_L=zeros(1,length(t_rebuilt));
for kk=1:1:numel(xfreq_orig);
aa_sig_rebuilt_L = array1(kk, 2)*cos ((array1(kk,1))*t_rebuilt+(array1(kk, 4)));
aa_sig_combined_L = aa_sig_combined_L + aa_sig_rebuilt_L;
end
sig_full_L=(aa_sig_combined_L/max(abs(aa_sig_combined_L))*.8);
我想出了这个作为矢量化的方法
I came up with this as vectorization
示例:
array1=[10,.4,.34,2.32;12,.3,.45,.4];
t_rebuilt=linspace(0,2*pi,44100)
aa_sig_rebuilt_L = array1(kk, 2).*cos ((array1(kk,1)).*t_rebuilt+(array1(kk, 4)));
aa_sig_combined_L = sum(aa_sig_rebuilt_L);
我不知道该怎么做是如何获取 kk 变量以逐步访问行
What I don't know how to do is how to get the kk variable to access the rows incrementally
谢谢.
推荐答案
一种选择是如下使用bsxfun
a = array1;
t = t_rebuilt;
aa_sig_rebuilt_L = bsxfun(@times, a(:,2) , ...
cos( bsxfun(@plus, bsxfun(@times, a(:,1), t), a(:,4)) ));
aa_sig_combined_L = sum(aa_sig_rebuilt_L);
请记住,这将比版本使用更多的内存(循环将使用numel(xfreq_orig)
倍的内存,因为它计算aa_sig_rebuilt_L
的每一行,然后才将它们累加,而循环则计算每一行,将其添加到总和,然后丢弃).
Bear in mind that this will use more memory than the version will a loop (it will use numel(xfreq_orig)
times as much memory, as it computes every row of aa_sig_rebuilt_L
before summing them, whereas the loop computes each row, adds it to the sum and then discards it).
当需要在不同大小的数组之间执行二进制运算时,例如使用bsxfun
函数. TxN
矩阵和Tx1
向量.在这种情况下,它将在矩阵的每一列和向量之间执行运算.
The function bsxfun
is used when you need to perform a binary operation between arrays of different sizes, e.g. a TxN
matrix and a Tx1
vector. In this case it would perform the operation between each column of the matrix and the vector.
在您的情况下,您有一个列向量和一个行向量,并且将运算应用于列向量的第i
个元素和行向量的第j
个元素,以获得<矩阵的第c8>个元素.
In your case you have a column vector and a row vector, and the operation is applied to the i
'th element of the column vector and the j
'th element of the row vector, to get the ij
'th element of a matrix.
这篇关于向量化Matlab/八度FOR循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!