Craig
Craig

Reputation: 11

Filter a matrix regarding a certain condition in one column

I have an array that defines an xyz point cloud. Very simply x,y and z with no other fields.

I load this into matlab without issue but now need to filter the z value. I would like to remove rows in the array dependent on preferred values. So for example if z is < than 5 remove this row. I thought the easy way would be to create a new array when finding a row that meets my criteria.

I tried this. Basically run through the whole array and each time I find a row inside my parameters Id like to write it to a new array. So if the first array has 220K columns and I say my new array must conatin z values greater than -5.4 then i should have a new array with less rows.

length = size (array, 1)
newarray= []
b=0;
for n = 1:length
  if array(n, 3) > -5.4 %I want to remove anything greater than -5.4 in the %third column
 %newarray = [newarray; array(n)];
  b = b+1
  end
end

Very simple but not for me!

Upvotes: 1

Views: 191

Answers (2)

Robert Seifert
Robert Seifert

Reputation: 25232

Simply do:

data = [ 1 2 7;
         1 3 3;
         1 2 8 ]

out = data(data(:,3) >= 5,:)  

which returns

data =
     1     2     7
     1     3     3
     1     2     8


out =
     1     2     7
     1     2     8

Have a look at that article about matrix indexing.

You first need to create a mask, you want the linear index of the rows where the value in the n-th column are bigger than X

mask = data(:,n) > X

and then you filter your data with that mask:

out = data(mask,:)

Upvotes: 4

RobertStettler
RobertStettler

Reputation: 11

I don't quite understand, how your array exactly looks like, but maybe this will help you

a=[1 2 3; 4 5 6; 1 2 7; 1 2 1; 3 2 1; 4 8 10; 2 3 1; 5 4 48];
a((a(:,3)>6),:) = []

Upvotes: 1

Related Questions