csg
csg

Reputation: 8186

In MATLAB, how to compare the elements of 2 vectors in the most efficient way?

I have a vector r, which stores the previously taken actions. Let,

r=[8,8,8,2,2,6,6, ... , 4,4,4];     % (8:up, 2:down, 4:left,  6:right)

and I have a second vector actions that indicates the currently available actions. Let,

actions=[2,6,8];
[~,n]=size(actions);

and let n indicate the number of available actions. I want to compare the last n elements of vector r with the elements of vector actions and eliminate the current action that is in the opposite direction i.e. to avoid repetitions.

For example, since in this case vector r indicates that the last action was towards left, in vector actions 6 should be eliminated and the result would be

actions=[2,8];

What is an efficient (i.e. ideally by avoiding loops) way of achieving this? Thanks.

Upvotes: 0

Views: 91

Answers (2)

Camilo Rada
Camilo Rada

Reputation: 456

I would define an array with the oposite actions, that in this case would be

oposite=[0 8 0 6 0 4 0 2]% (8:up, 2:down, 4:left,  6:right)

Then, to remove from actions the ones that have been used in tha last n you just use bsxfun to do singleton expansion of the equal function, so that actions would be:

actions(any(bsxfun(@eq,oposite(actions)',r(end-n+1:end)),2))=[];

That's it, just one line once 'oposite' is defined.

Upvotes: 4

Aero Engy
Aero Engy

Reputation: 3608

I solved it by defining a matrix that held the opposite action pairs. Then takes the last n- unqiue values of r and removes its pair from the actions array.

pairs = [2 8;...
         8 2; ...
         4 6; ...
         6 4];

r=[8,8,8,2,2,6,6,4,4,4];  
actions=[2,6,8];
[~,n]=size(actions);

%The unique last n-values of r
lastN_r   = unique(r(end-n+1:end));
%Where these are in the pairs matrix
matchI    = ismember(pairs(:,1),lastN_r);
%Remove them.
parsedAct = actions(~ismember(actions,pairs(matchI,2)))

parsedAct =    
     2     8

Upvotes: 0

Related Questions