how to vectorize this for loop

7 Ansichten (letzte 30 Tage)
serena dsouza
serena dsouza am 30 Jan. 2018
Kommentiert: Jan am 31 Jan. 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 Kommentar
Jan
Jan am 31 Jan. 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.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by