Relational operations of vectors of different length

I am working with two arrays. The first array is data sampled at each time step, so is of length let's say nTimeSteps. The second array is data sampled at sequential physical positions, so the array has length let's say nPositions. What I would like to do is return an array of the index of the position sample array that yields the value just less than the time sample value. For example,
timeData = [3 7 9 13]; positionData = [2 4 6 8 10 12 14];
I would like to return an array A = [1 3 4 6], because positionData(A) = [2 6 8 12] which are the values just less than [3 7 9 13]. Hopefully this is clear. The array A would have the same length as timeData.
I cannot do this in a loop because the arrays can be very large. Is there a fast or vectorized method to do this? I am having a hard time because the vectors are not of the same length.

 Accepted Answer

I didn't check how this will handle large inputs (and you didn't specify how large is large), but this doesn't involve a loop:
arrayfun(@(x) max(positionData(x>positionData)),timeData)

1 Comment

This was a good solution for the size I was using, thank you!

Sign in to comment.

More Answers (2)

for k=1:numel(timeData)
idx=find(positionData>timeData(k),1)-1;
out(k)=positionData(idx);
end
display(out)
This will take in account only values strictly inferior
[c,id]=sort([timeData,positionData]);
out=c(find(ismember(id,1:numel(timeData)))-1);

Community Treasure Hunt

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

Start Hunting!