how to vectorize this for loop

6 ビュー (過去 30 日間)
serena dsouza
serena dsouza 2018 年 1 月 30 日
コメント済み: Jan 2018 年 1 月 31 日
[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 件のコメント
Jan
Jan 2018 年 1 月 31 日
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.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by