how to vectorize this for loop

8 visualizzazioni (ultimi 30 giorni)
serena dsouza
serena dsouza il 30 Gen 2018
Commentato: Jan il 31 Gen 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 Commento
Jan
Jan il 31 Gen 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.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by