vectorizing a matlab / octave FOR loop

送分小仙女□ 提交于 2019-12-23 04:49:26

问题


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

Example:

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);

What I don't know how to do is how to get the kk variable to access the rows incrementally

THanks.


回答1:


One option is to use bsxfun as follows

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);

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).

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.

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.



来源:https://stackoverflow.com/questions/20400933/vectorizing-a-matlab-octave-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!