2

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?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Shinobii
  • 2,401
  • 5
  • 24
  • 39
  • 2
    As a side note, the reason why your code extracts the first column is [linear indexing](https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html) – Luis Mendo Jun 20 '23 at 16:27

1 Answers1

4

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]);
Wolfie
  • 27,562
  • 7
  • 28
  • 55