help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: help with vectorizing a for loop


From: Jordi Gutiérrez Hermoso
Subject: Re: help with vectorizing a for loop
Date: Tue, 4 Oct 2011 17:54:34 -0500

On 3 October 2011 05:09, Rick T <address@hidden> wrote:

> I have a for loop that reads an array but I would like to vectorize
> it to see if will improve speed. at the moment the for loop takes
> about 7 mins any ideas to speed this up

> The array called inner_freq has three columns made up of
> amplitude,frequency, and phase

> for ii=1:1:length(inner_freq)-1
>  
> aa_sig_rebuilt=inner_freq(ii,2)*cos(2*pi*t*inner_freq(ii,1)+inner_freq(ii,3));
>      aa_sig_combined=aa_sig_combined+aa_sig_rebuilt;
> end;

Well, this seems to work for me, but the speed up is barely
noticeable. Is this what you wanted? Your loopy version, assuming I
got it right, takes 0.7s here. Not 7 minutes.

I'm using broadcasting here, available in the dev version. If you're
using an older version of Octave or Matlab, replace

    a .* b

with

    bsxfun(@times, a, b)

HTH,
- Jordi G. H.

----------------------------------------------------------------------

inner_freq = rand(8193,3);
t = rand(1,15679);
aa_sig_combined = 0;

tic,
for ii=1:1:length(inner_freq)-1
  aa_sig_rebuilt = inner_freq(ii, 2)*cos (2*pi*t*inner_freq(ii, 1) +
inner_freq(ii, 3));
  aa_sig_combined = aa_sig_combined + aa_sig_rebuilt;
end;
toc

tic,
aa_sig_combined2 = sum(inner_freq(:, 2)*cos (2*pi*t.*inner_freq(:, 1)
+ inner_freq(:, 3)));
toc

assert(aa_sig_combined2, aa_sig_combined);


reply via email to

[Prev in Thread] Current Thread [Next in Thread]