how to vectorize this for loop

5 visualizaciones (últimos 30 días)
serena dsouza
serena dsouza el 30 de En. de 2018
Comentada: Jan el 31 de En. de 2018
[mrows,ncols] = size(spec);
if (mrows==1) mrows=ncols; ncols=1; spec = spec(:); end
% ---- edit out NaNs and Infs ---------------------------------------
good = isfinite(spec);
rmin = min(spec(good)) - 1;
bad = find(~isfinite(spec));
if (~isempty(bad))
spec(bad) = ones(size(bad)) * rmin;
end
[mrows,ncols] = size(spec);
if (mrows==1) mrows=ncols; ncols=1; spec = spec(:); end
% ---- edit out NaNs and Infs ---------------------------------------
good = isfinite(spec);
rmin = min(spec(good)) - 1;
bad = find(~isfinite(spec));
if (~isempty(bad))
spec(bad) = ones(size(bad)) * rmin;
end
[mrows,ncols] = size(spec);
if (mrows==1) mrows=ncols; ncols=1; spec = spec(:); end
% ---- edit out NaNs and Infs ---------------------------------------
good = isfinite(spec);
rmin = min(spec(good)) - 1;
bad = find(~isfinite(spec));
if (~isempty(bad))
spec(bad) = ones(size(bad)) * rmin;
end
val = ones(npicks,ncols) * NaN ;
loc = zeros(npicks,ncols) ;
for k=1:ncols
% Find all local peaks:
dx = diff([rmin; spec(:,k); rmin]); % for a local peak at either end
lp = find(dx(1:mrows) >= 0 ...
& dx(2:mrows+1) <=0); % peak locations
vp = spec(lp,k); % peak values
for p=1:npicks
[v,l] = max(vp); % find current maximum
val(p,k) = v; loc(p,k) = lp(l); % save value and location
ind = find(abs(lp(l)-lp) > rdiff); % find peaks which are far away
if (isempty(ind))
break % no more local peaks to pick
end
vp = vp(ind); % shrink peak value array
lp = lp(ind); % shrink peak location array
end
end
  1 comentario
Jan
Jan el 31 de En. de 2018
I assume, that you do not want to vectorize the code, but to accelerate it. Vectorized code is not necessarily faster. But what should be the purpose of suggesting slower code?!
Optimizing code without the possibility to run the code, is based on guessing. Please provide some relevant input data, e.g. produced by rand with a typical dimension. It matters, if the inputs are huge (some GB) and you run this function once only, or if you want to process billions of small arrays.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by