MATLAB: Determining if two column adjacent values in a matrix cross over any values in a vector

MATLABmatrix manipulation

Hi there,
I have a matrix (attached as ExampleMatrix.mat), where I want to find where two adjacent column values "cross over" values of a separate vector.
Simpler example with only two columns:
TestMatrix = [...
0,0.533459574621213;
18.5334595746212,18;
36,36.5334595746212;
54,54.5334595746212;
72,72.5334595746212;
90,90.5334595746212;
108,108.533459574621;
126,126.533459574621;
144,144.533459574621;
162,162.533459574621;
180,180.533459574621;
198,198.533459574621;
216,216.533459574621;
234,234.533459574621;
252,252.533459574621;
270,270.533459574621;
288,288.533459574621;
306,306.533459574621;
324,324.533459574621;
342,342.533459574621...
];
TestTarget = [18.25; 306.25];
So far I've been looping over pairs of columns over the values of TestTarget like so:
% Find the difference between two adjacent columns
DifferenceVector = diff(TestMatrix, 1, 2);
% Find + differences
pV_ = sign(DifferenceVector) == 1;
% Find - differences
nV_ = sign(DifferenceVector) == -1;
for i = size(TestTarget, 1);
% For + differences, see if target value is crossed over
passingFromLeft(pV_) = TestMatrix(pV_, 1) + DifferenceVector(pV_) > TestTarget(i);
passingFromRight(pV_) = TestMatrix(pV_, 2) - DifferenceVector(pV_) <= TestTarget(i);
% For - differences, see if target value is crossed over
passingFromLeft(nV_) = TestMatrix(nV_, 1) + DifferenceVector(nV_) < TestTarget(i);
passingFromRight(nV_) = TestMatrix(nV_, 2) - DifferenceVector(nV_) >= TestTarget(i);
passingFromLeft & passingFromRight
end
ans =
20×1 logical array
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
ans =
20×1 logical array
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
Is there a more efficient method to do this without looping over the values of TestTarget, for multiple columns?

Best Answer

  • After sorting the matrix so that minimum values of each row are on the left, you just need one line to find the intervals that 'skip over' the targets.
    % Sort matrix so min val is always on left
    TMsort = sort(TestMatrix,2);
    result = (TMsort(:,1) < TestTarget.') & (TMsort(:,2) > TestTarget.');
    • * TestTarget in your example is a column vector. It must be a row vector in the line above which is why it's transposed.
    • * Column 'n' of the 'result' matrix corresponds to TestTarget(n).
    Results:
    result =
    20×2 logical array
    0 0
    1 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0
    0 1
    0 0
    0 0
    However, the data you attached in the mat file contains 101 columns so I'm not sure what needs adapted from this 2-column solution. In other words, are you just conserned with the first and last column (assuming they are sorted)?