Selection of array elements according to a certain rule

So I have a 100000 by 2 matrix in MATLAB. I only want to extract items in the second column that have the same item for the corresponding row in the first column. For example. if we have:

A = [1  2
     3  4
     2  6
     1  5
     4  1
     1  3]

      

and then indicate that we want all the items in the second column with to 1

match the value in the first column. So I would like the above to be:

2
5
3

      

Does anyone know how to do this in MATLAB?

+3


source to share


1 answer


Matlab supports matrix operations, so you can do what you want without explicitly looping the entire matrix like some other languages.

Using boolean indexing (more on this here https://www.mathworks.com/help/matlab/math/matrix-indexing.html?refresh=true ) you can extract the required elements from your matrix.

First, you want to create an array of [0,1] rows in your matrix that satisfies your condition.

You can do it with A (:, 1) == 1

This will create



1 0 0 1 0 1

This means that the first, fourth, and last rows satisfy the condition when an element in the first column of the matrix satisfies the condition that it is equal to one.

Now you can use this to create elements in the second column by simply using it as the index of your original matrix.

A (A (:, 1) == 1,2)

to get the desired result.

+1


source







All Articles