Moving Norm using Vectorization

Hi everyone,
I was wondering how to calculate the "moving norm" of a vector. For example, suppose I have a vector v1 = [a b c d e];
I want to calculate the moving norm involving 3 elements. The first element of the output will be incomplete because we haven't had time to "move over" the vector v1.
The first element of the output array is: norm([0 0 a])
The second element of the output array is: norm([0 a b])
The third element of the output array is: norm([a b c])
The fourth element of the output array is: norm([b c d])
...
The last element of the output array is: norm([e 0 0])
It would be good if all the elements are in one vector, and that vector could be calculated quickly using vectorization. I am already aware of solving this problem using a loop, but I am curious about how to do this faster.
Thank you very much for your help in advance.

 채택된 답변

Oleg Komarov
Oleg Komarov 2011년 8월 29일

0 개 추천

% Example input
v = rand(10,1);
% Window length
w = 3;
% Pad with zeros
o = zeros(w-1,1);
v = [o;v;o];
% Calculate index [0 0 a; 0 a b; ...]
pos = 0:numel(v)-w;
idx = bsxfun(@plus, pos.', pos(1:w)+1);
% Euclidean norm sqrt(a^2 + b^2 ...)
out = sqrt(sum(v(idx).^2,2));

댓글 수: 4

Jrand
Jrand 2011년 8월 29일
Thank you. nV should be numel(v).
Oleg Komarov
Oleg Komarov 2011년 8월 30일
Edited.
Walter Roberson
Walter Roberson 2011년 8월 30일
What if numel(v) < w ? :-)
Oleg Komarov
Oleg Komarov 2011년 8월 30일
MATLAB will start swearing uncomprehensible stuff :).
DISCLAIMER: no checks.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 8월 29일

2 개 추천

t = hankel([zeros(1,length(v1)-1) v1]);
out = sqrt(sum(t(1:length(v1),:).^2));
Knew I'd find a use for hankel() someday!

댓글 수: 1

bym
bym 2011년 8월 29일
@Walter - I was just working on an answer that involved hankel, glad you beat me to the punch +1 vote

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2011년 8월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by