0

I have an Nx2 matrix say D(k1,k2).I have to compare k1 and k2 from each row and switch accordingly. There is another vector d(i) which has M values. if k1 and k2 is any one value of d(i) I have to switch. if D(k1,1)==d(i)&&D(k1,2)==d(i).... Is there any method to compare all the d(i) elements in the if loop without using a for loop for i?

1
  • So if I understand correctly: you want the two elements of a row in the D matrix to switch places, when they both appear in the vector d? Commented Mar 1, 2012 at 10:29

2 Answers 2

1

You can use the ismember function for checking if the vector d contains certain values:

D_in_d = ismember(D,d);

and then you still have to loop to perform the flipping operation on specific rows:

for i=1:size(D,1)
    if all(D_in_d(i,:))
        D(i,:)=fliplr(D(i,:));
    end
end
Sign up to request clarification or add additional context in comments.

Comments

0

This is relatively easy to accomplish with matlab's vectorizion without any loops at all.

% A swap logical vector ( 1 if you need to swap that row, 0 otherwise)

swap_logical = ( ismember(D(:,1),d) | ismember(D(:,2),d) );

% Vectorized swapping based on the swap boolian.

Dnew = swap_logical.*D(:,2:-1:1) + ~swap_logical.*D;

2 Comments

As ismember already provides logical output I would recommend a simple or statement: swap_logical = ismember(D(:,1),d) | ismember(D(:,2),d)
I agree that is more straight forward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.