how speed up or avoid loops

2 次查看(过去 30 天)
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

采纳的回答

Matt Fig
Matt Fig 2012-8-24
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;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by