Search code examples
arraysmatlabmatrix

MATLAB extract columns of array based on value of another column


I have a large matrix A, which is of size 105000 x 3. I would like to extract the first two columns of the matrix, whenever the third column = Val.

I have tried:

Test = A(A(:,3) == Val);

However, this only extracts the first column. I cannot seem to figure out the syntax to pull out the first and second columns. I know to simply pull out the first two columns it would be Test = A(:, [1,2]), so I imagine I need to combine these somehow?


Solution

  • You need

    Test = A(A(:,3) == Val, 1:2);
    

    or equivalently

    Test = A(A(:,3) == Val, [1,2]);
    

    The index after the comma dictates the columns, the index before the comma dictates the rows.

    Note that equating floating point numbers with == can give unexpected results, you might be better off doing something like

    tol = 1e-10; % some small tolerance value
    Test = A( abs(A(:,3) - Val) < tol, [1,2]);