Sliding window to calculate intra-window difference

I have a matrix s=512*100*20 (with N=100). I want to implement sliding window of a width 2W+1 that is centered at position i to compute the intra-window difference s(i+w)-s(i-w) for every possible position. I have attached the algorithm. Anyone, please help me how to implement it in Matlab.

 Réponse acceptée

The formula in the attachment is written below. I don't know what your value W is and I don't now how your variable N comes into play.
% deltaW = nan(?,?); %allocate your loop variable here after you know what its size should be.
for i = W : N-1-W
deltaW(i) = s(i+W) - s(i-W);
end

5 commentaires

Thank you @Adam for your reply. I think I have not described my problem well. Let me try again.
Actually, I have a signal 'g' 100*11, where 100 is length 'N' of the signal. My algorithm requires arranged data matrix stored in variable "data" so I have first sorted the signal 'g' by amplitude and arranged the "data" according to indexes of 'g'. Now I have to implement the sliding window on this arranged data to compute intra-window difference. I implemented it in same way as you suggested but I am getting error of 'invalid index' in tmp1(:,W-i,:). Can you please have a look at my code and algorithm again.
load s %size(s)=[100*11] load data; % size(data)=[512*100*20*11] [N, nt]=size(s); % N=100, nt=11 W=3; % Randomly selected
for ii=1:nt % I want loop to iterate 11 times tmp1=data(:,:,:,ii); % defining temporary virable for sorting [~,index]=sort(s(:,ii),'descend'); %sorting signal s tmp1=tmp1(:,index,:); % arrange my data accroding to signal s for i=W:N-1+W % applying window according to formula dff(:)= tmp1(:,i+W,:)-tmp1(:,W-i,:); end
end
load s %size(s)=[100*11]
load data; % size(data)=[512*100*20*11]
[N, nt]=size(s); % N=100, nt=11
W=3; % Randomly selected
for ii=1:nt % I want loop to iterate 11 times tmp1=data(:,:,:,ii); % defining temporary virable for sorting [~,index]=sort(s(:,ii),'descend'); %sorting signal s tmp1=tmp1(:,index,:); % arrange my data accroding to signal s for i=W:N-1+W % applying window according to formula dff(:)= tmp1(:,i+W,:)-tmp1(:,W-i,:); end
end
Adam Danz
Adam Danz le 24 Sep 2018
Modifié(e) : Adam Danz le 24 Sep 2018
On the first iteration of your ii-loop, W equals i (they both equal 3). When you subtract i from W, you get 0. 0 is not a valid index in Matlab. You can't take the 0th position. That's why this line fails.
tmp1(:,W-i,:)
In other languages (i.e. C++) 0 is a valid index. For example
p = [8 7 6 5];
p(0) = 8
but in Matlab
p(1) = 8.
So you need to adapt the formula to Matlab's syntax like this.
...
for i = W : N-1-W
deltaW(i) = s(i+W+1) - s(i-W+1);
end
Thank you @Adam for your kind reply
Glad I could help.

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by