Search code examples
matlabfindcontinuous

finding non-continuous values under loops in matlab


Would you please help me sort this following problem out? I've been stuck here for a while.

I have the data as below. You can see there are 3 loops (column A, B and C) and column D contains the computed values that I want at the index continuous positions.

enter image description here

However these indexes are not continuous at all. You can see at 3rd-loop (column C), it nicely goes from 1-4 but then the next loop it misses 3...and so on. Consequently, the 2nd-loop doesn't go nicely also. These non-continuous are marked by red number or line...

What I want is the interpolated values in column D in case there are a gap between them, a simple interpolation is already great for me.

Say my loops go from 1:nA, 1:nB and 1:nC. For this very short example, nA=2, nB=3, nC=4 but my true data is up to hundreds...


Solution

  • Suppose you have in variable A the first set of indices, in B the second set of indices, in C the third set of indices, and in D the values. First, you need to put those in order in an array, then interpolate the missing values:

    %'Calculate the max indices'
    nA = max(A);
    nB = max(B);
    nC = max(C);
    
    %'Calculate the linear indices out of subscripts'
    I = nB*nC*(A(:)-1) + nC*(B(:)-1) + C(:);
    
    %'Interpolate the values'
    V = interp1(I, D(:), transpose(1:nA*nB*nC), 'linear');
    

    You can try fancier interpolation methods by consulting the help: http://www.mathworks.com/help/matlab/ref/interp1.html