Borrar filtros
Borrar filtros

how speed up or avoid loops

1 visualización (últimos 30 días)
Jeff Eriksen
Jeff Eriksen el 24 de Ag. de 2012
Comentada: Jeff Eriksen el 4 de Feb. de 2014
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

Respuesta aceptada

Matt Fig
Matt Fig el 24 de Ag. de 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;
  1 comentario
Jeff Eriksen
Jeff Eriksen el 4 de Feb. de 2014
a belated "Thak you", -Jeff

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by