필터 지우기
필터 지우기

Quick vectorization question (for loop)

조회 수: 2 (최근 30일)
Tanmay
Tanmay 2012년 9월 27일
Hi
This loop takes about 0.085 seconds to execute and needs to be executed several thousand times. Is there a way you think I can vectorize this? I really appreciate any help!
wsize = 20;
vin = rand(1200,1);
for idx = wsize:length(vin)
mstd(idx-wsize+1, :) = std(vin(idx-wsize+1:idx));
end
PS: I don't have Parallel Processing toolbox.

채택된 답변

Matt Fig
Matt Fig 2012년 9월 27일
편집: Matt Fig 2012년 9월 27일
I hope you are pre-allocating your mstd vector. Other than that, this is about 6 times faster. I didn't compare to stdfilt.
for idx = wsize:length(vin)
x = vin(idx-wsize+1:idx);
x = x-sum(x)./ wsize;
mstd(idx-wsize+1, :) = sqrt(sum(x.^2)/(wsize-1));
end
.
.
.
EDIT add comparison based on IA's recommendation
I find the above to not be faster than using stdfilt when repeatedly run. Here is what I used for comparison:
mstd2 = stdfilt(vin,[0;ones(wsize,1)]);
mstd2 = mstd2(wsize/2:end-wsize/2);
There might be a better way to do this with stdfilt, I have no real experience with the function and had to figure it out based on trial and error and doc reading... Perhaps IA can comment.
  댓글 수: 1
Tanmay
Tanmay 2012년 9월 27일
yes, I had pre-allocated this vector. Nice trick there! Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 9월 27일
Do you have the Image Processing Toolbox? it looks like your code is a sliding window of a standard deviation filter. This is done by the function stdfilt() in the Image Processing Toolbox. Alternatively (if you don't have the Image Processing Toolbox) you could use an anonymous function and blockproc (I have a demo for that if you need it).
  댓글 수: 1
Matt Fig
Matt Fig 2012년 9월 27일
I had never heard of stdfilt, IA. Thanks!

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by