0
votes

I have a n-by-3 matrix. Like so:

  mtx =  [3 1 3;
          2 2 3;
          2 3 2;
          5 4 1]

I want the end result to be:

mtx2 = [0 0 0;
        2 2 3;
        2 3 2;
        0 0 0]

So I want to put zeros on the rows that don't have the first number as another, and that their 2nd number doesn't equal the 3rd of another.

Imagine that the first number of any row is 'a', the 2nd 'b', and the 3rd 'c'. For row #1 I will compare it's 'a' with all other 'a's. If there isn't another 'a' equal to that, then row #1 changes to [0 0 0]. But if there is another 'a' equal to that one, for instants in row #2, I will compare 'b' #1 and 'c' #2. If they are equal those rows stay the same. If not row #1 changes to [0 0 0]. And so on.

2

2 Answers

2
votes

See if this works for you -

%// Logical masks of matches satisfying condition - 1 and 2
cond1_matches = bsxfun(@eq,mtx(:,1),mtx(:,1).')  %//'
cond2_matches = bsxfun(@eq,mtx(:,3),mtx(:,2).')  %//'

%// Create output variable as copy of input and use the conditions to set
%// rows that satisfy both conditions as all zeros
mtx2 = mtx;
mtx2(~any( cond1_matches & cond2_matches ,1),:)=0
0
votes

I'd search through this way, testing your two criteria against each row.

Izeros=[];  % here is where I'll store the rows that I'll zero later
for Irow = 1:size(mtx,1) %step through each row

    %find rows where the first element matches
    I=find(mtx(:,1)==mtx(Irow,1));

    %keep only those matches that are NOT this row
    J=find(I ~= Irow);

    % are there any that meet this requirement
    if ~isempty(J)
        %there are some that meet this requirement.  Keep testing.

        %now apply your second check, does the 2nd element
        %match any other row's third element?
        I=find(mtx(:,3)==mtx(Irow,2));

        %keep only those matches that are NOT this row
        J=find(I ~= Irow);

        % are there any that meet this 2nd requirement
        if ~isempty(J)
            %there are some that meet this 2nd requirement.
            % no action.
        else
            %there are none that meet this 2nd requirement.
            % zero the row.
            Izeros(end+1) = Irow;
        end
    else
        %there are none that meet the first requirement.
        % zero the row.
        Izeros(end+1) = Irow;
    end
end