user1965021
user1965021

Reputation: 31

How do you pick out rows from an array based on a specific value in a column?

I have an array of data. For simplicity, let's call it a 4 x 3 matrix. Let's say I want to find a data point in column 2 that has a value of 5. Then, I want to take all rows that contains the value of 5 in column 2 and place it in its own array. My data is much larger than the one displayed below, so I don't want to go through by eye and look at every line of data and identify all the 5's.

  % My idea of the code:

  data = [1 2 3 4; 5 5 5 6; 6 4 5 6]

  if data(:,2) == 5

  % This is the part I can't figure out

  end

Let's call the finaldata the array in which the data with 5's will be stored. How do I do this?

Upvotes: 3

Views: 225

Answers (2)

You can use the FIND Function to search that value, and give the coords back (it might be a vector) to retrieve the rows:

data(find (data(:,2)==5),:)

Why not using logical indexing: Performance

Upvotes: 0

tzelleke
tzelleke

Reputation: 15345

You should use logical indexing:

all_fives_rows = data(data(:, 2) == 5, :)

Upvotes: 6

Related Questions