how speed up or avoid loops
2 views (last 30 days)
Show older comments
I think there must be ways to avoid for loops, but have not found the correct magic matlab syntax for doing so. Can someone suggest how I might make the following more efficient? -Jeff
% example.m
% how can I speed up inner loop(s) here?
% create random array of signals (Nchannel x Nframes)
% for each pair of signals compute difference wave
% for each wave, integrate over moving window Nwin wide
% will be flat epochs at beginning and end of integrated difference waves,
% Hwin wide
nchan = 4;
nprs = nchan*(nchan-1)/2;
nfrm = 1000;
data = rand(nchan,nfrm)-0.5;
new = zeros(nprs,nfrm);
hwin = 10;
nwin = 2 * hwin + 1;
fnwin = single(nwin);
ipr = 0;
for ich = 1:nchan-1
for jch = ich+1:nchan
ipr = ipr + 1;
dif = data(jch,:) - data(ich,:);
rsum = 0;
for ifr = hwin+1:nfrm-hwin
sum = 0;
for jfr = ifr-hwin:ifr+hwin
sum = sum + dif(jfr);
end
new(ipr,ifr) = abs(sum/fnwin);
end
end
end
0 Comments
Accepted Answer
Matt Fig
on 24 Aug 2012
This is much faster. Note that you are masking a very valuable MATLAB function by naming a variable 'sum' in your loop! Please stop doing this or you will end up spending an awful lot of time debugging why the SUM function is broken in your copy of MATLAB!
nchan = 4;
nprs = nchan*(nchan-1)/2;
nfrm = 1000;
data = rand(nchan,nfrm)-0.5;
new = zeros(nprs,nfrm);
hwin = 10;
nwin = 2 * hwin + 1;
fnwin = single(nwin);
ipr = 0;
idx = ones(nwin,nfrm-2*hwin);
idx(:,1) = 1:nwin;
idx = cumsum(idx,2);
for ich = 1:nchan-1
for jch = ich+1:nchan
ipr = ipr + 1;
dif = data(jch,:) - data(ich,:);
new(ipr,hwin+1:nfrm-hwin) = sum(dif(idx));
end
end
new = abs(new)/fnwin;
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!