Search code examples
arraysmatlabvectorsamplingresampling

Downsampling, or equalizing vector lengths in matlab


I'm having somewhat of a basic problem yet I can't seem to solve it. I have two very large pieces of data. I have a matrix A that is 48554 x 1 and and a matrix B that is 160272 x 1. What I want to do is "downsample" matrix B so that it is of the same length as matrix A. Moreover, I want a function that can do this for pretty much any large m x 1 and n x 1 matrices (so that it works for more than this specific example). I tried using the resample function like so:

resample(B,length(A),length(B))

However I'm getting an error indicating that the filter length is too large. Next I tried using a for loop to simply extract every ith element from matrix B and save it into a new matrix, but this was not working out so nicely since the vector lengths aren't divisible by an integer. Does anyone have other (hopefully simple) ways to accomplish this?


Solution

  • You could try using the interp1 function. I know that down-sampling isn't really interpolating per se. Here's an example:

    x1 = [0:0.1:pi];%vector length is 32
    x2 = [0:0.01:pi];% vector length is 315
    
    y1 = sin(x1);
    y2 = sin(x2);
    
    %down sample y2 to be same length as y1
    y3 = interp1(x2,y2,x1);%y3 length is 32
    
    figure(1)
    plot(x2,y2);
    hold on
    plot(x1,y1,'k^');
    plot(x1,y3,'rs');
    
    % in general use this method to down-sample (or up-sample) any vector:
    % resampled = interp1(current_grid,current_vector,desired_grid);
    % where the desired_grid is a monotonically increasing vector of the desired length
    % For example:
    
    x5 = [0.0:0.001:1-0.001];
    y5 = sin(x);
    % If I want to down sample y5 to be 100 data points instead of 1000:
    y6 = interp1([1:length(y5)],y5,1:1:100);
    
    % y6 is now 100 data point long. Notice I didn't use any other data except for y6, the length of y6 and my desired length.