how to vectorize this for loop
조회 수: 6 (최근 30일)
이전 댓글 표시
[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
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 Exchange에서 Data Type Conversion에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!