Preetha
Preetha

Reputation: 1

Matlab loop inside loop

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?

Upvotes: 0

Views: 243

Answers (2)

Geoff_Reck
Geoff_Reck

Reputation: 1

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;

Upvotes: 0

Gunther Struyf
Gunther Struyf

Reputation: 11168

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

Upvotes: 1

Related Questions