Resample function is not working properly and damaging the signal

58 visualizzazioni (ultimi 30 giorni)
Hi,
I have a question regarding the resample function (It is the documentation under "Resample Multichannel Signal"). In this function, I realized that the function damages the signal on both ends of the given signal. Here I am attaching the code to generate 100-sample sinusoidal signal.
p = 3;
q = 2;
tx = 0:p:300-p;
x = cos(2*pi*tx./(1:5)'/100);
plot(tx,x,'.:')
title('Original')
ylim([-1.5 1.5])
However, once you resample with the following give code, the signals are simply damaged at both ends. You can see the effects on both time points close to 0 and close to 300.
ty = 0:q:300-q;
y = resample(x,p,q,'Dimension',2);
plot(ty,y,'.:')
title('Upsampled')
Therefore, could you please help me to solve this issue? Because, I am currently trying to resample my multichannel motion capture signals, which are sampled at 60 Hz or 200 Hz, in "100 Hz". However, this function will damage my signal if I use it, and this will definitely affect the outcome of my research.
I will be waiting for your help and appreciate your assistance.
Thanks!
  6 Commenti
Paul
Paul il 17 Mar 2023
The doc page resample says that the function "compensates for the delay introduced by the filter," which is the exact language used by lowpass et. al. I'm nearly certain that the filtering in lowpass is effectively the same as filtfilt, which does extend the input signal off the edges to minimize these types of edge transients. I'm suprised that resample doesn't do the same; maybe there is something particular about the filtering in resample that precludes that (assuming it is, in fact, not done as appears to be the case).
Bob S
Bob S il 22 Set 2023
Modificato: Bob S il 22 Set 2023
Hi,
I do have an additional comment regarding the post by @goksu avdan. There is an issue with using resample() for processing blocks of data. If I'm using resample to interpolate/decimate, I will get erroneous results at the edges. In the past, to get around this, I have used a "brute-force" approach with filter() as in the following:
while dataAvailable
% Say x is dimensioned 1 by Nsamples and I am upsampling by a factor
% Nup and downsampling by Ndown
% Zero fill between samples
xi = [x;zeros(Nup-1,Nsamples)];
xi = xi(:).';
% xi should now be dimensioned 1 by (Nup*Nsamples) with zeros inbetween the original samples
% Now low-pass filter and decimate
[xd, zFilt] = filter(bFilt, 1, xi, zFilt);
xd = xd(1:Ndown:end);
end
Assuming that I use the same bFilt that would come out of resamp(), the above result will match resample() if I ignore the first floor(length(bFilt)/2/Ndown) output samples. By using the above approach, I have to deal with a transient response for the first block, after that I have continuous correct results. In order to achieve that with resample, one would have to devise some kind of overlap-save approach.
The problem with the "brute force" approach is that it is inefficient and does not take advantage of all of the zeros that a proper polyphase filtering technique, as done in resample(), would handle.
What would be ideal would be something like:
[y, zFilt] = resmaple(x, p, q, zFilt);
I do realize that depending on what the ratio of p/q looks like, it might be near impossible to get an integer number of output points without "playing tricks", but I'm ignoring that right now.
Any thoughts on this? Am I missing something? Apologies for spelling errors and any code miscues.
Thanks in advance!

Accedi per commentare.

Risposta accettata

Star Strider
Star Strider il 16 Mar 2023
I had not noticed the ‘end effect’ problem before (although I use resample relatively frequently, and that is clearly visible in the signals in the resample documentation). Looking at the original resampled waveforms, it occurred to me that the waveforms that were zero at both ends didn’t have that probllem. I devised a single-line linear regression for another problem recently, and decided to use it here to first ‘detrend’ the signals so that they began and ended at zero, resample them, and then ‘retrend’ them to their original orientations.
This may not be perfect, since it uses resample on the detrended signals, however it does elliminate the ‘end effect’ problem.
I am not certain what other processing you’re doing, so experiment with it to see how it works with your signals in that context —
p = 3;
q = 2;
tx = 0:p:300-p;
x = cos(2*pi*tx./(1:5)'/100);
figure
plot(tx,x,'.:')
title('Original')
ylim([-1.5 1.5])
legend(compose('%d',1:5), 'Location','best')
ty = 0:q:300-q;
% y = resample(x,p,q,'Dimension',2);
Fs = 1/(ty(2)-ty(1));
LR = @(X,Y,x,y) [X(:) ones(size(X(:)))] * ([x(:) ones(size(x(:)))] \ y(:)); % Single-Line Linear Regression
for k = 1:size(x,1)
DeTr = LR(tx,x(k,:),tx([1 end]),x(k,[1 end])).';
[y(k,:),ty] = resample(x(k,:)-DeTr,tx,Fs,'Dimension',2);
ReTr = LR(ty,y(k,:),tx([end 1]),x(k,[end 1])).';
y(k,:) = y(k,:)+ReTr;
end
figure
plot(ty,y,'.:')
title('Upsampled')
legend(compose('%d',1:5), 'Location','best')
.
  14 Commenti
goksu avdan
goksu avdan il 18 Mar 2023
Hi,
Thanks for the warning. I haven't done the part you mentioned. I am also going to save each of these cell arrays (or in my version it is simply assigned to the different variable) seperately, and will not be overwritten later. So, if you are asking if this is intentional, yes it was for me. Because, I didn't write that part of the code, yet. But, I have the code which can simply perform the detrending, resampling, and re-trending without any issue for each "n" in the for loop.
Regarding INTERP1, this function is not giving the same results I am looking for: This is from another post on Matlab: "The difference between interpolation (the interp1 function) and resampling (the resample function) in MATLAB is that resample is designed to resample signals, and so incorporates a FIR anti-aliasing filter. The interp1 function does not, so if you are going to do signal processing with an interpolated signal use resample, not interp1."
Stephen23
Stephen23 il 18 Mar 2023
Modificato: Stephen23 il 18 Mar 2023
"Using the inbuilt INTERP1 is even simpler than downloading a third-party function."
I did not want to imply that INTERP1 replaces RESAMPLE, only that INTERP1 is a simpler replacement for Star Strider's detrend and retrend function, exactly as I showed here:
I realize that my comment was ambiguous on this.

Accedi per commentare.

Più risposte (2)

Paul
Paul il 17 Mar 2023
Modificato: Paul il 17 Mar 2023
Hi goksu,
The observed behavior is documented at resample specifcally here: "... resample assumes that the input sequence, x, is zero before and after the samples it is given. Large deviations from zero at the endpoints of x can result in unexpected values for y." See examples at that doc page.
If you're looking for theoretically pleasing approach, resample provides means to influence transients as shown here, for example. Don't know if that approach applies to the ends of the signal or just transients internal to the signal as shown in that example.
If you're looking for a heuristic approach, one option might be to extrapolate the signal off the ends, apply resample, then chop of the extensions. I used 20 sample extensions and linear extrapolation on the example data. The actual number and method will likely depend on the actual data and the resample filter parameters. I'm only thinking about extrapolations that minimize transients at the transitions to/from the endpoints of the original signal before resampling. spline or pchip might work better. Anyway, here's what I tried:
Original signals
p = 3;
q = 2;
tx = 0:p:300-p;
x = cos(2*pi*tx./(1:5)'/100);
plot(tx,x,'.:')
title('Original')
ylim([-1.5 1.5])
Extend the signals by 20 samples via linear extrapolation.
txext = [(-20:-1)*p tx (1:20)*p+tx(end)];
xext = (interp1(tx,x.',txext,'linear','extrap')).';
Resample
y = resample(xext,p,q,'Dimension',2);
fsx = 1/p;
fsy = fsx*p/q;
ty = txext(1) + (0:(size(y,2)-1))/fsy;
Plot the extended output, note the transients have been pushed away from the central region we care about 0 < t < 300.
figure;
plot(ty,y),grid
Lop off the extensions
y(:,ty<0) = [];
ty(ty<0) = [];
y(:,ty>tx(end)) = [];
ty(ty>tx(end)) = [];
figure
plot(ty,y),grid
  4 Commenti
goksu avdan
goksu avdan il 17 Mar 2023
Hi Star Strider,
I posted the error under your main answer. It already is on the updated answer of mine below.
Yes, the end of data is important. You were right about it. Is Paul's answer affecting the end of the data so much or not when you extend on both ends? Because, his code worked fine for now without any error. Maybe, I can just update his answer with Spline interpolation instead of linear interpolation.
Regarding the detrended data, it is an useful approach; however, the signal I have didn't quite work well in resample function, and gave an error of "not matching dimensions". It is most likely I understand something wrong, and messed up with the code.
Paul
Paul il 17 Mar 2023
I don't think I deleted any needed data at the ends; I certainly didn't mean to if I did. The resampled, post-extraploated data is retained for all times contained within the original tx vector, including the endpoints.

Accedi per commentare.


Stephen23
Stephen23 il 18 Mar 2023
Modificato: Stephen23 il 18 Mar 2023
It is easy to avoid the loop too, it is just a simple linear interpolation:
p = 3;
q = 2;
tx = (0:p:300-p).';
x = cos(2*pi*tx./(1:5)/100); % note orientation!
plot(tx,x,'.:')
title('Original')
ylim([-1.5,1.5])
ty = 0:q:300-q;
ax = interp1(tx([1,end]),x([1,end],:),tx);
ay = interp1(ty([1,end]),x([1,end],:),ty);
y = resample(x-ax,p,q)+ay;
plot(ty,y,'.:')
title('Upsampled')
  2 Commenti
Stephen23
Stephen23 il 18 Mar 2023
Modificato: Stephen23 il 18 Mar 2023
Note that you can easily avoid all of those loops and all of the superfluous data processsing.
Avoid fighting MATLAB with lots of loops and IFs and the like. Think in terms of arrays and indices.
S = load('Subject3.mat');
S = S.s;
% Select valid dataset:
X = strcmp({S.Data.Task},'Walking');
Y = cellfun(@(m)any(isnan(m(:))),{S.Data.Marker});
Z = find(X&~Y,1,'last');
old = S.Data(Z).Marker;
% Sample rate:
p = interp1([60,200],[5,1],S.KinFreq);
q = interp1([60,200],[3,2],S.KinFreq);
tx = p*(0:size(old,2)-1);
Fs = 1/q;
% Resample:
DeTr = interp1(tx([1,end]),old(:,[1,end]).',tx).';
[M,ty] = resample(old-DeTr,tx,Fs,'Dimension',2);
ReTr = interp1(ty([1,end]),old(:,[1,end]).',ty).';
new = M+ReTr;
% Plot original:
figure
plot(tx, old)
grid
xlabel('Time')
ylabel('Signal')
title('Original Vectors')
% Plot resampled:
figure
plot(ty, new)
grid
xlabel('Time')
ylabel('Signal')
title('Resampled Vectors')
goksu avdan
goksu avdan il 18 Mar 2023
Hi,
You are right, and the code you have looks a lot simplier! I can definitely avoid from the for loops and I know it. But, I did not have enough confidence and experience to perform all of these calculations. Since I do know how to do it with for loops, and I chose to do with this way. Thanks for the code!

Accedi per commentare.

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by