walexwisdom
walexwisdom

Reputation: 11

How to use for loop to delete rows of similar second column element in matlab

I have this matrix:

A=[2,2,4;1,2,3;4,5,6;4,5,6;4,5,6;7,8,9]

How can I use a for loop to delete a row that has its second column element the same as the previous row second column element in matlab? The objective is to arrive at:

A=[2,2,4;4,5,6;7,8,9]

Upvotes: 0

Views: 88

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 14939

No loop needed!

What you can do here is create a logical vector with true in the places where there is a difference between the second columns, and false where the value is equal:

This can be achieved using diff like this: diff(A(:,2))~=0. Now, you need to include the first row too, so add a true in the start of this vector: [true; diff(A(:,2))~=0)]. Use this vector to choose which rows you want, and use : to make sure you get all the columns:

A=[2,2,4;1,2,3;4,5,6;4,5,6;4,5,6;7,8,9]
B = A([true; diff(A(:,2))~=0],:)
B =    
   2   2   4
   4   5   6
   7   8   9

Upvotes: 5

RCaetano
RCaetano

Reputation: 673

I think this sample code can do the task:

A=[2,2,4;1,2,3;4,5,6;4,5,6;4,5,6;7,8,9]

% First row will always be the same of the A matrix
res_mat(1,:) = A(1,:);
row = 2;

for i = 2 : size(A,1)
  if A(i,2) ~= A(i-1,2)
    res_mat(row,:) = A(i,:);
    row = row + 1;
  end
end

res_mat

HTH ;)

Upvotes: 0

Related Questions