简体   繁体   中英

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 ie 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 (ie ideally by avoiding loops) way of achieving this? Thanks.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM